You have a file with 100 billion URLS, find first unique URL.
Design a data structure for following operations in O(1) time.:
insert
remove (FIFO)
find MODE
Design an LRU cache, where you remove an element not only by time lapsed since last used but also by a cost associated with each element. F(t, c) is a method to find weight for each element. Where c is cost and t is time since last used.
Implement DFS
After I implemented this, I was told to implement it without recursion. He told me to write pseudo code. I wrote it using stacks.
Given a matrix (0,0 is to the botto9m left like co-ordinate system)of 0s and 1s and two co-ordinates find if there is a path between them, Also you can only travel via 1s and you can only go up or right.
Answer: Backtracking algorithm
given K sorted arrays merge them
Answer: Told him how to do using merge of merge sort. He wanted me to do another approach I googled later you can use min heap for it.
Given an array of integers find the element for which the sum of left = sum of right. example -1 100 1 98 1 should return index of 1 i.e 2
Answer: First told him about Brute Force approach and then told him if we can iterate once and get the total sum
int findIndex(A){
int sum =0;
for(int i =0;i<A.lenght;i++)
{
sum+= A[i];
}
int lSum=0;
for(int i=0;i<A.length;i++)
{
int rsum = sum - lsum-A[i];
if(lsum==rsum)
return i;
lsum += A[i];
}
return -1;
}Given a string having a number:
"625626628"
Here the substrings are in consecutive order except for 1 substring which is missing. Find the missing substring.
Test cases:
"1235678" -> 4 is missing
"9979981000" -> 999 is missing
"624625627" -> 626 is missing
Write a function which will return a char from a given encoded string from given index without decoding string. e.g. from “a2bc3d4” ( means “aabcbcbcdddd” ) and index value is 7 means function should return c without decoding original string ?
Inplace reverse a sentence
You given a sentence of english words and spaces between them.
Nothing crazy:
1) no double spaces
2) no empty words
3) no spaces at the ends of a sentence
void inplace_reverse(char* arr, int length) {
// your solution
}Example:
input "I wish you a merry Christmas"
output "Christmas merry a you wish I"
Constrains: O(1) additional memory
[[del]]
The closest common ancestor in a tree forest.
class Node {
Node* parent; // == null for root of tree
Node* left;
Node* right;
}
Node* tree_forest[]; // array of pointers which points to roots of each tree respectively
Node* closest_common_ancestor(Node* n1, Node* n2) {
// your solution
}Example:
| a | j
| / \ | /
| b c | h
| / / \ |
|d e f |for e and d CCA is a
for e and f CCA is c
for e and c CCA is c
for h and d CCA is null
Constrains: O(1) additional memory
3> write program to find wrong no of "(()" parenthesis in expression "((B+a)"
give error for "((A))" - for unnecessary brackets
2> write program to mirror the binary tree.
1> write program to calculate power(x,n) in log(n) time
Design a URL system.
He even wanted to know what kind of algorithm to use, improve the speed, availability etc.
Given a 4 X 4 game slot that has random alphabets in all the slots
Write a function that takes the keyboard and the word as input and returns true if the word can be formed
False otherwise.
A word can be formed on the board by connecting alphabets adjacent to each other (horizontal, vertical and diagonally)
Same alphabet should not be reused.
Given a set of n people, find the celebrity.
Celebrity is a person who:
1. Knows only himself and no one else
2. Every one else knows this person
You are given the following helper function:
bool knows(i, j);
Returns:
True: If i knows j
False: otherwise
I proposed the O(n2) algorithm at first but he wanted me to improve on it. He wanted an O(n) algorithm
You have a list of words with ranking.
Now you need to create a function that will take this list as input and provide a way so that a T9 keyboard can provide three top results of probable words based on rankings for the numbers punched in.
You are given a series like this:
(1,2)
(2,3)
(5,6)
(2,9)
Every element in this series is a pair(u,v) which means that there is a connection between (u,v).
Output group of elements:
For instance, if you look at the above series, the output will be:
[1,2,9], [5,6]
Design a TinyURL like Service.
A book contains with pages numbered from 1 - N. Imagine now that you concatenate all page numbers in the book such that you obtain a sequence of numbers which can be represented as a string. You can compute number of occurences 'k' of certain digit 'd' in this string.
For example, let N=12, d=1, hence
s = '123456789101112' => k=5
since digit '1' occure five times in that string.
Problem: Write a method that, given a digit 'd' and number of its occurences 'k', returns a number of pages N. More precisely, return a lower and upper bound of this number N.
Example:
input: d=4, k=1;
output {4, 13} - the book has 4-14 pages
input d=4 k=0;
output {1, 3} - the book has 1-3 pages
By tossing a coin we can get either head or tail, i have a function toss() which return head or tail with equal probability.
You have to write a function for dice which will return number from 1-6 with equal probability.
constraints : you can not use random function, you can use only toss function.
Tree to List: convert a binary tree to a circular doubly-linked list
You are given a String of number characters (S), like the following for example:
"132493820173849029382910382"
Now, let's assume we tie letters to numbers in order such that:
A = "0"
B = "1"
C = "2"
...
M = "12"
N = "13"
...
Y = "24"
Z = "25"
Write an algorithm to determine how many strings of letters we can make with S, by converting from numbers to letters.
We can find the minimum of an integer array in n operations. We can find the maximum of an integer array in n operations.
How can we find both the min and max of an integer arrays in less than 2n operations?
Hint: Specifically in 3n/2 + c operations
you have experience with a 3x3 Sudoku.Think about 2*2 sudoku:
The array has 4 rows and 4 columns.
The numbers 1, 2, 3 and 4, each appears exactly once in each row.
The numbers 1, 2, 3 and 4, each appears exactly once in each column.
The numbers 1, 2, 3 and 4, each appears exactly once in the 2x2 square formed by the intersection of rows 1, 2 and columns 1, 2.
The numbers 1, 2, 3 and 4, each appears exactly once in the 2x2 square formed by the intersection of rows 1, 2 and columns 3, 4.
The numbers 1, 2, 3 and 4, each appears exactly once in the 2x2 square formed by the intersection of rows 3, 4 and columns 1, 2.
The numbers 1, 2, 3 and 4, each appears exactly once in the 2x2 square formed by the intersection of rows 3, 4 and columns 3, 4.
Your task is:
1. Count all possible different solutions of the 2*2 sudoku.
2.Print all solutions.
3.Store all solutions.
Write a function to determine if a string is a number without using any built-in function.
public bool IsNumber(string num)
{
}You are given an array of integers 'a' that can fit in a memory. Write a method that retuns an array of the same lenght such that each element 'i' of this array is a sum of 'a' except the element a[i]. You are not allowed to use '-' operator.
Design a site similar to junglee.com. Assume you are given a crawler, design a distributed system , what ds will you use , some basic api’s etc.
You have a file with 100 billion URLS, find first unique URL.
Design a data structure for following operations in O(1) time.:
insert
remove (FIFO)
find MODE
Design an LRU cache, where you remove an element not only by time lapsed since last used but also by a cost associated with each element. F(t, c) is a method to find weight for each element. Where c is cost and t is time since last used.
Implement DFS
After I implemented this, I was told to implement it without recursion. He told me to write pseudo code. I wrote it using stacks.
Given a matrix (0,0 is to the botto9m left like co-ordinate system)of 0s and 1s and two co-ordinates find if there is a path between them, Also you can only travel via 1s and you can only go up or right.
Answer: Backtracking algorithm
given K sorted arrays merge them
Answer: Told him how to do using merge of merge sort. He wanted me to do another approach I googled later you can use min heap for it.
Given an array of integers find the element for which the sum of left = sum of right. example -1 100 1 98 1 should return index of 1 i.e 2
Answer: First told him about Brute Force approach and then told him if we can iterate once and get the total sum
int findIndex(A){
int sum =0;
for(int i =0;i<A.lenght;i++)
{
sum+= A[i];
}
int lSum=0;
for(int i=0;i<A.length;i++)
{
int rsum = sum - lsum-A[i];
if(lsum==rsum)
return i;
lsum += A[i];
}
return -1;
}Given a string having a number:
"625626628"
Here the substrings are in consecutive order except for 1 substring which is missing. Find the missing substring.
Test cases:
"1235678" -> 4 is missing
"9979981000" -> 999 is missing
"624625627" -> 626 is missing
Write a function which will return a char from a given encoded string from given index without decoding string. e.g. from “a2bc3d4” ( means “aabcbcbcdddd” ) and index value is 7 means function should return c without decoding original string ?
Inplace reverse a sentence
You given a sentence of english words and spaces between them.
Nothing crazy:
1) no double spaces
2) no empty words
3) no spaces at the ends of a sentence
void inplace_reverse(char* arr, int length) {
// your solution
}Example:
input "I wish you a merry Christmas"
output "Christmas merry a you wish I"
Constrains: O(1) additional memory
[[del]]
The closest common ancestor in a tree forest.
class Node {
Node* parent; // == null for root of tree
Node* left;
Node* right;
}
Node* tree_forest[]; // array of pointers which points to roots of each tree respectively
Node* closest_common_ancestor(Node* n1, Node* n2) {
// your solution
}Example:
| a | j
| / \ | /
| b c | h
| / / \ |
|d e f |for e and d CCA is a
for e and f CCA is c
for e and c CCA is c
for h and d CCA is null
Constrains: O(1) additional memory
3> write program to find wrong no of "(()" parenthesis in expression "((B+a)"
give error for "((A))" - for unnecessary brackets
2> write program to mirror the binary tree.
1> write program to calculate power(x,n) in log(n) time
Design a URL system.
He even wanted to know what kind of algorithm to use, improve the speed, availability etc.
Given a 4 X 4 game slot that has random alphabets in all the slots
Write a function that takes the keyboard and the word as input and returns true if the word can be formed
False otherwise.
A word can be formed on the board by connecting alphabets adjacent to each other (horizontal, vertical and diagonally)
Same alphabet should not be reused.
Given a set of n people, find the celebrity.
Celebrity is a person who:
1. Knows only himself and no one else
2. Every one else knows this person
You are given the following helper function:
bool knows(i, j);
Returns:
True: If i knows j
False: otherwise
I proposed the O(n2) algorithm at first but he wanted me to improve on it. He wanted an O(n) algorithm
You have a list of words with ranking.
Now you need to create a function that will take this list as input and provide a way so that a T9 keyboard can provide three top results of probable words based on rankings for the numbers punched in.
You are given a series like this:
(1,2)
(2,3)
(5,6)
(2,9)
Every element in this series is a pair(u,v) which means that there is a connection between (u,v).
Output group of elements:
For instance, if you look at the above series, the output will be:
[1,2,9], [5,6]
Design a TinyURL like Service.
A book contains with pages numbered from 1 - N. Imagine now that you concatenate all page numbers in the book such that you obtain a sequence of numbers which can be represented as a string. You can compute number of occurences 'k' of certain digit 'd' in this string.
For example, let N=12, d=1, hence
s = '123456789101112' => k=5
since digit '1' occure five times in that string.
Problem: Write a method that, given a digit 'd' and number of its occurences 'k', returns a number of pages N. More precisely, return a lower and upper bound of this number N.
Example:
input: d=4, k=1;
output {4, 13} - the book has 4-14 pages
input d=4 k=0;
output {1, 3} - the book has 1-3 pages
By tossing a coin we can get either head or tail, i have a function toss() which return head or tail with equal probability.
You have to write a function for dice which will return number from 1-6 with equal probability.
constraints : you can not use random function, you can use only toss function.
Tree to List: convert a binary tree to a circular doubly-linked list
You are given a String of number characters (S), like the following for example:
"132493820173849029382910382"
Now, let's assume we tie letters to numbers in order such that:
A = "0"
B = "1"
C = "2"
...
M = "12"
N = "13"
...
Y = "24"
Z = "25"
Write an algorithm to determine how many strings of letters we can make with S, by converting from numbers to letters.
We can find the minimum of an integer array in n operations. We can find the maximum of an integer array in n operations.
How can we find both the min and max of an integer arrays in less than 2n operations?
Hint: Specifically in 3n/2 + c operations
you have experience with a 3x3 Sudoku.Think about 2*2 sudoku:
The array has 4 rows and 4 columns.
The numbers 1, 2, 3 and 4, each appears exactly once in each row.
The numbers 1, 2, 3 and 4, each appears exactly once in each column.
The numbers 1, 2, 3 and 4, each appears exactly once in the 2x2 square formed by the intersection of rows 1, 2 and columns 1, 2.
The numbers 1, 2, 3 and 4, each appears exactly once in the 2x2 square formed by the intersection of rows 1, 2 and columns 3, 4.
The numbers 1, 2, 3 and 4, each appears exactly once in the 2x2 square formed by the intersection of rows 3, 4 and columns 1, 2.
The numbers 1, 2, 3 and 4, each appears exactly once in the 2x2 square formed by the intersection of rows 3, 4 and columns 3, 4.
Your task is:
1. Count all possible different solutions of the 2*2 sudoku.
2.Print all solutions.
3.Store all solutions.
Write a function to determine if a string is a number without using any built-in function.
public bool IsNumber(string num)
{
}You are given an array of integers 'a' that can fit in a memory. Write a method that retuns an array of the same lenght such that each element 'i' of this array is a sum of 'a' except the element a[i]. You are not allowed to use '-' operator.
Design a site similar to junglee.com. Assume you are given a crawler, design a distributed system , what ds will you use , some basic api’s etc.
Give an architecture diagram with all entities and relationships of a multi user wysiwyg editor . basically a web interface to multiple authors who can edit and store their docs . multiple ppl should be able to save it at once . also ownership should be present for documents
Design a site similar to junglee.com. Assume you are given a crawler, design a distributed system , what data structure will you use , some basic api’s etc.
roll two dice, what is the probability of rolling no sixes?
To deploy a module inside kernel, what are the possible methods.? Mention actual difference among them.
Given two binary trees, A and B,
we can define A as a subset of B if the root of A exists in B and if we can superimpose A on B at that location without changing B. (That is, the subtrees from the root of A and the node in B that is the same as the root of A are the same),
Example:
A:
5
4 7
B:
6
5 12
4 7 8 10
A is a subset of B in this case.
B1:
6
5 12
4 7 8 10
1
A is still a subset of B1, even though B1 extends one more level than A.
Write an algorithm to determine if one tree is a subset of another tree
Write a code to find if a link list is palindrome . Linklist consists variable string at each node. for eg
a->bcd->ef->g->f->ed->c->ba
The above given linklist is palindrome and func shd return - True
Write a program to reverse contents of a file in place..for example if file has "abcde" after executing program the contents should be "edcba". The program should be efficient.. You can use fwrite & fread apis...
I wrote using fread and fwrite, by reading 1 char at a time and replacing with one at the other end.. He seemed not happy as the I/O was high...
in one string array{'Good',''word','good','woRd'...}
how can i print like Good--2
Word-2 times appeared in the array.even Good and good are different in case sensitive.
IN phone directory,i have like below details
ABc---123
bcd--345
cda--523
abc--678.
So if i want to see Abc person phone numbers we should get the both the numbers,how can we implement this in java
You have String array like{'cat','good','tac','act''....} like some 1000 words.
So if i give input tac ,output should be cat and act..
How can we implement with less complexity
We have rectangular and inside many rectangular were drawn.So if we click on main Rectangular we should get the count of rectangular's ..For this how can we implement in java
Given a sorted doubly linked list, write an algorithm to convert this list into a binary search tree (BST). The BST will be used to represent a set. You may expect that client will use it to search for presence of a key in the set.
You may assume that you are given the following Node implementation that you can not exted or modify:
public class Node {
public Node prev, next;
public int key;
}You algorithm is not allowed to create any other instance of the Node.
We have a Very big which our datatypes does not provide.
We need to multiply such numbers, how to do?
example :
Num1 = {1,2}, Num2 = {1,0} then ans would be {1,2,0}
Num1 ={5,3,6,2,8,2,0,2,8}, num2 ={3,5,2,3,2,1,}
then ans would be the multiplication value of 5362882028 X 352321
You to find the shortest palindrome string by adding 0 or more characters on the right side of the string.
for example:
string is java then answer would be avajava
string is enm then mnemn
string is aavaa then aavaa
How to implement your own Hashmap?
You have infinite number of 3Rs coins and 5Rs coins. And your are provided one random number and u need to find out that whether you can make the amount with both denominations.
for example:
U r given a number: 23 then 5*4 +3 = 23 so true
U r given a number :16 then False.
You have a string and you need to find the shortest palindrome string from that string by adding 0 or more characters on right side of the string.
example:
String is java then answer would be avajava
String is emme then emme
String is hcasach
How to implement your own HashMap??
How to handle the collision using some chaining technique?
We have a Very big which our datatypes does not provide.
We need to multiply such numbers, how to do?
example :
Num1 = {1,2}, Num2 = {1,0} then ans would be {1,2,0}
Num1 ={5,3,6,2,8,2,0,2,8}, num2 ={3,5,2,3,2,1,}
then ans would be the multiplication value of 5362882028 X 352321
You have infinite number of 3Rs coins and 5Rs coins. And your are provided one random number and u need to find out that whether you can make the amount with both denominations.
for example:
U r given a number: 23 then 5*4 +3 = 23 so true
U r given a number :16 then False.
Find out the least recent occurred message.
Suppose your are getting message in streams, and you add it using add("M1").
You need to find out the least recent occurred message at any point of time.
for example,
Add("M1')->Add("M2') then LROM=M1
Add("M1')->Add("M2')->Add("M1') then LROM =M2
Add("M1')->Add("M2')->Add("M1')->Add("M3')-> then LROM =M2
Hope question is clear.
Given an array of integers, return true if there're 3 numbers adding up to zero (repetitions are allowed)
{10, -2, -1, 3} -> true
{10, -2, 1} -> true -2 + 1 +1 =0
Find the maximum number of non-intersecting events in a calendar.
Print all subset of a given set which sums up to ZERO
{8,3,5,1,-4,-8}
so ans will be : {8,-8}
{3,5,-8}
{3,1,-4}
size of set can be upto 50 but elemet of set can be as big as 18 digit number
Hi ,
Given a set of number eg {5,3,1,8, -8,-4}
Print all subset which will sum up to ZERO
for eg {3,1,-4} {5,3,-8}, {8,-8}
Note : size of subset can be max 100 and element can be very big like 13 or 14 digit number
Write a function to print the rows of a binary tree, terminating each row with a carriage return
I have interview with Ericsson:
Working knowledge of server-side JavaScript
Working knowledge of WSDL, XSD and XML
Working knowledge of workflow concepts such as BPM, BPMN, BPML and BPEL.
Working knowledge of HTML
Working knowledge of integration technologies/frameworks including AXIS, SOAP, JMS, HTTP, Socket, FTP, SMTP/POP and integration platforms (EAI, ESB, BPI) such as JMS, MQ, WLI and Tibco
Good design skills
please help if anyone gone through interview process of Ericson.
Imagine a large city like Los Angeles. Suppose someone shows up at location A, then N minutes later at location B. Design a function that approximates the probability they passed a Starbucks.
You are given a string 's' and you are given a dictionary of english words. You goal is to write an algorithm that returns all words from the dictionary the can be formed by characters from that string 's'.
Example:
s = "ogeg"
following words can be formed from 's': go egg ego . . .
Further it is given that string 's' always consists of four lower case characters. Lets say that the dictionary is contained in a file and can be fitted in the memory. It is up to you which data structure you use to represent the dictionary.
How would you design an efficient algorithm? Follow up: What if the dictionary file can not be fitted in the memory?
A program that prints all combinations of a n letter word without using recursion technique.
Example :
Word : abcd
abcd
bacd
cabd
acbd
bcad
cbad
dbac
bdac
adbc
dabc
badc
abdc
acdb
cadb
dacb
adcb
cdab
dcab
dcba
cdba
bdca
dbca
cbda
bcda
why isn't this algorithm working ??
public class quest {
public static void main (String[] args) {
int n =3 ;
int base =2 ;
int remainder =0 ;
String new=" " ;
while (n>0) {
remainder =(n/base) ;
n=(n/base) ;
new=remainder+new ;
}
System.out.println(new) ;
}
}
}
what is the output of the following and justify ?
#include <stdio.h>
int main()
{
printf(&unix["\0c%set\012"],(unix)["chak"]+"Trick"-0x67);
}
Given a table of [Url, Content] pairs produce a new table of [Url, Set of duplicate Urls].
Example Input:
a.com => <html>a</html>
b.com => <html>b</html>
c.com => <html>c</html>
d.com => <html>a</html>
e.com => <html>a</html>
Example Output:
a.com => [d.com, e.com]
b.com => []
c.com => []
Consider a two dimensional co-ordinate system with two axes; X & Y. This system is identified by positive integer co-ordinates. Meaning, every valid point in this system is represented by two values (x, y) where 0 < x,y <100.
You are given an input set of lines, specified by the co-ordinates of the two end-points.
Write a program to identify all closed shapes created by the specified lines.
Input Format (the program should accept this simple text file called "input.txt" placed in the classpath):
A1, B1; C1, D1 A2, B2; C2, D2 … An, Bn; Cn, Dn
Expected Output (based on actual values of the input lines):
There are two triangles and 1 square based on the input. Triangle 1 with vertices (a1,b1; a2, b2; a3,b3) Triangle 2 with vertices (a5,b5; a6, b6; a7, b7) Square 1 with vertices (a8, b8; a9, b9; a10, b10; a11, b11)
Good day I just got a question which is the following
you have an vector like this
[JFK, LXA, SNA, RKJ, LXA, SNA]
each 2 group define a route. so,
JFK -> LXA
SNA -> RKJ
LXA -> SNA
Find the path from departure to destination. note: departure and destination are not known.
The final destination should be
JFK-> LXA -> SNA -> RKJ
The function signature is something like this
vector<string> findPath(vector<string> airports)
{
}
The airports (nodes) cannot be duplicated and the path should print all the airports (nodes)
Good day I just got a question which is the following
you have an vector like this
[JFK, LXA, SNA, RKJ, LXA, SNA]
each 2 group define a route. so,
JFK -> LXA
SNA -> RKJ
LXA -> SNA
Find the path from departure to destination. note: departure and destination are not known.
The final destination should be
JFK-> LXA -> SNA -> RKJ
The function signature is something like this
vector<string> findPath(vector<string> airports)
{
}
The needed the full path from departure to destination, and you can only pass by one point only once.
Thanks!
Given a binary search tree (BST), write a mehtod that will convert this BST into a doubly linked list that is sorted (ascending or descending order) and returns the first element in this list. You may assume you are given following Node class:
public class Node {
public Node left, right;
public String val;
}Example: The following BST
G
/ \
A T
can be converted into a list
A = G = T
Do it in place! Hnce the memory complexity of your algorithm shoul be O(1).
#include <stdio.h>
int main()
{
printf(&unix["\0c%set\012"],(unix)["chak"]+"Trick"-0x67);
}
What all Smoke test cases should be performed, if a defect fix is given for a module C. Data will come to module C if its integrated with other Modules say A , B.
Given a Tree:
A
/\
B C
/\ /\
D E F GWrite a function that prints:
A
BC
DEFG
in how many ways we can assign a major minor number to any device?
How can I represent the following in a data structure ?
<html><body><div><span>TEXT1</span><br/></div></body></html>
Do I do the same using a stack or create a tree for the same ?
There are Some team owners who want to communicate with other team owners through some mediators regarding player transfer mechanism.A team owner has to consult more than 1 mediator in order to talk with some other team owner and at least one mediator is required to carry out talk between team owners.Each mediator can have maximum of 2 mediator under it and a mediator which has no mediator under it will have atleast one team owner and at max 2 team owners under it .A mediator which has at least one mediator under it will not have any team owner under it . Your task is to find the maximum number of mediators between talk of any two team owners.
Java coding
Given a file with the following entry
ID EMp_Name Manager_ID
1 "ABC" 2
2 "PRW" Null
3 "DEF" 2
4 "PRE" 3
5 "DKF" 4
Print the Respective Manager hierarchy in the below format
PRW | ABC |
| DEF | PRE | DKF
The Employe Manager table can be extended to Hold N entry
boolean checkPattern(String str)
{
// Implementation
}
Implement the method checkPattern. str is a string argument.
Return true: if the string is following any pattern
example: xyzxyzxyz
Here "xyz" is the pattern
return false: String is not following pattern
example: xyzxyzA
A is not in part of pattern.
1) You have a folder full of .bin files that are proprietary.
2) You have a class called converter with a "binToTSV" method which you can pass the name of a .bin file and will generate a .tsv file.
3) The TSV file is a tab separated value file with a key on each line, and a value next to it spaced with a tab as such.
-------
num_connections 65
latency_ms 70
bandwidth 20
.... //etc.
-------
Q: Write a method to calculate the average latency and total bandwidth.
Design and Implement a Telephone database structure in which a Customer Entry has PhoneNum,Name,Address.
a) Given any PhoneNum return all the Customer details
b) Given any Name list all the Entries (As Name can be duplicate, only PhoneNum is unique)
c) Also Name searching should support Prefix Based.
Given an array of ages (integers) sorted lowest to highest, output the number of occurrences for each age.
For instance:
[8,8,8,9,9,11,15,16,16,16]
should output something like:
8: 3
9: 2
11: 1
15: 1
16: 3
This should be done in less than O(n).
Having A List of int [1,1,1,3,1,2,1,1,4,1]
Output needed [1,5,6,3,7,2,8,9,4,10]
Note: Need not to change value of 3,2,4
To find the number of groups and output the groups:
Explanation: To find the sum of the elements in the groups and that sum should be divisible by input X and the groups should be limited to range with X numbers.
If X is 3, then the group should have only 2 elements and 3 elements from the array whose sum is divisible by 3.
Input:
Array: 3, 9, 7, 4, 6, 8
X: 3
Output:
3, 9
3, 6
9, 6
3, 9, 6
No of groups: 4
how to design a relation functionality. similar to facebook , how to hold friends objects for a user profile , so that that is easily searchable . how to use cache for this?
How can you design a data structure that can do the following operations in O(1) time:
Insert, Delete, Search, Max which returns the maximum number
I know delete, search and insert can be done O(1) time in a hashmap with a proper hash function. But not sure Max is even possible in O(1) with the presence of delete operation?
You are given two integer arrays A and B .
1<=i<=len(A) so i is iterator of array A
1<=j<=len(B) so j is iterator of array B
find all the pairs(i,j) such that : i < j and A[i]>B[j]
Constructing Bridges:
A River that cuts through a set of cities above and below it. Each city above the river is matched with a city below the river.
Construct as many Non-Crossing Bridges as possible.
Input:
Above Bank >> 7 4 3 6 2 1 5
Below Bank >> 5 3 2 4 6 1 7
are given in pairs: (7,5) (4,3) (3,2) (6,4) (2,6) (1,1) (5,7)
Output:
(1,1) (3,2) (4,3) (6,4) (7,5)
You have given a mathematical expression in string format.
Example: "3+12*3-4/7"
You need to write function which will return final result of the given expression. Don't use Expression Tree and start scanning from left to write.
It should be bug free.
you have a sparse matrix with negative values almost 100 times the positive value. How will you retriev these negative values.
The interviewer was expecting something else other than just negative values.
He said look at it as a table where each seller has negative values for products he doesnt sell. He just wanted a subset of maybe all the negative values.
A 2D matrix is given to you. Now user will give 2 positions (x1,y1) and (x2,y2),
which is basically the upper left and lower right coordinate of a rectangle formed within the matrix.
You have to print sum of all the elements within the area of rectangle in O(1) running time.
Now you can do any pre computation with the matrix.
But when it is done you should answer all your queries in constant time.
Example : consider this 2D matrix
1 3 5 1 8
8 3 5 3 7
6 3 9 6 0
Now consider 2 points given by user (0, 2) and (2, 4).
Your solution should print: 44.
i.e., the enclosed area is
5 1 8
5 3 7
9 6 0
A 2D matrix is given to you. Now user will give 2 positions (x1,y1) and (x2,y2), which is basically the upper left and lower right coordinate of a rectangle formed within the matrix. You have to print sum of all the elements within the area of rectangle in O(1) running time.
Now you can do any pre computation with the matrix.
But when it is done you should answer all your queries in constant time.
Example : consider this 2D matrix
1 3 5 1 8
8 3 5 3 7
6 3 9 6 0
Now consider 2 points given by user (0, 2) and (2, 4).
Your solution should print: 44.
i.e., the enclosed area is
5 1 8
5 3 7
9 6 0.
You are given a file which contains 3 values - start time, end time, amount of water flowing between the start time and end time for one day
The start time and end time may overlap and are inclusive. The times are not in a sorted order
Example:
0,10,100
10,15,300
16,20,400
5,15,200
Find the max flow of water at any instant of time.
In the above example, the answer is 600 ( at instant 10)
Design an algo to decide if the GO game is over. i.e.
Given a boolean matrix, write a code to find if an island of 0's is completely surrounded by 1's.
I have used my personal google API key here, you can use that or generate your own.
The response id JSON:
{
"destination_addresses" : [ "Sector 15, Faridabad, Haryana, India" ],
"origin_addresses" : [ "GBN School, Sector 21D, Faridabad, Haryana 121001, India" ],
"rows" : [
{
"elements" : [
{
"distance" : {
"text" : "6.1 km",
"value" : 6054
},
"duration" : {
"text" : "12 mins",
"value" : 716
},
"status" : "OK"
}
]
}
],
"status" : "OK"
}
Base Algorithm or the rule engine for scheduling:
For the examples, let us assume pincode 121001, with 3 cabs cab1, cab2 & cab3.
The time slots are:
9:00 am to 10:30 am, 10:30 am to 12:00 pm, 12:00 pm to 1:30 pm, 2:30 pm to 4:00 pm, 4:00 pm to 5:30 pm and 5:30 pm to 7:00 pm
Non-real time scheduling
For an appointment of any time slot, say 4:00 pm to 5:30 pm, check the cabs allotted for adjacent slots, 2:30 pm to 4:00 pm and 5:30 pm to 7:00 pm for this example.
1) If no cabs are allotted for adjacent slots, then assign any random cab, say cab1.
2) Else, say cab2 is allotted to slot 2:30 pm to 4:00 pm and cab3 to 4:00 pm and 5:30 pm. Using google distance matrix api (referred to as gdm api from now on), find which cab is within x kms (x should be configurable, e.g 5 kms would be a good start) of the new appointment.
2.1) If one of the cabs is within x kms, assign it to this time slot.
2.2) If both cabs are within x kms, assign the one that is closer. If the difference is imperceptible, assign one randomly.
2.3) If both cabs are more than x kms, assign it to cab1
2.4) If cab1 was also allotted one of the adjacent time slots, then assign the nearest cab to this time slot. If the difference is imperceptible, assign one randomly.
Real time scheduling
This is applicable for appointments for the same day.
The same algorithm can be used, but use time to travel from the gdm api, instead of distance, since it accounts for traffic.
Feel free to discuss details or suggest changes in the rule engine.
Print a BST such that it looks like a tree (with new lines and indentation, the way we see it in algorithms books).
You are given a Matrix of 0's and 1's. An element at (i,j) is connected to another element at (i+-1, j+-1) if both of them are 1. Find the number of clusters formed by this.
Answer: use dfs or bfs to traverse and then mark those positions with -1.
There is a one test case on a ui side i.e a form that you entered incorrect data. It will throw an error meassage
i.e a failed test case. It works on the test envoronment.
But it fails on ci tool jenkins. Onlly the failed testcase fails on build tool. How do you debug the issue? Logs and test environment it works?
2) I have a large sets of test data(lbulk records). How will you handle in automation frame work?
I have a few questions on automation framework(that was asked in the interview).
I have 1000 test cases. I am adding a test case in
1) I have 1000 test cases. I am adding a test case in the middle (501). What are some of the issues you faced in the framework?idata related)
Given a binary search tree and a number n, write a program to find the greatest number in the binary search tree less than or equal to N.
Given the following tree construction, what is the output for N=44?
This question was asked in the chat, just adding here with the solution. I don't know for which company it is.
Replace wild cards with all possible combinations of zeros and ones using recursion.
Input String: 0?1?
Output: 0010, 0011, 0110, 0111This is my solution using recursion:
import java.util.*;
public class ReplaceWildcardsRec {
public static List<String> expandString(String s, int i) {
List<String> l = new ArrayList<String>();
if(i>s.length()-1) {
l.add("");
return l;
}
for(String expanded: expandString(s,i+1)) {
if(s.charAt(i)=='?') {
l.add('0'+expanded);
l.add('1'+expanded);
}
else {
l.add(s.charAt(i)+expanded);
}
}
return l;
}
public static void main(String[] args) {
List<String> l = new ArrayList<String>();
String s = "1111?";
l = expandString(s,0);
System.out.println(l);
}
}Sort two sorted Linked Lists.
Write your own implementation of structs / classes you might need to use.
Try to come up with the best time and space complexity.
I ran out of time after merging the two lists in O(n) time and O(1) space, but I am guessing he wanted to expand the solution to implement a merge sort algorithm for an unsorted Linked List.
write boundary test cases for whether a linked list is circular linked list or not?
Write a java program logic to find whether list is circular
linked list or not?
Write a function that takes the following inputs and gives the following outputs.
Input: A list of points in 2-dimensional space, and an integer k
Output: The k input points closest to (5, 5), using Euclidean distance
Example:
Input: {(-2, -4), (0, 0), (10, 15), (5, 6), (7, 8), (-10, -30)}, k = 2
Output: {(5, 6), (7, 8)}
Implement strcmp function of stdlib.h library without using any standard library.
Implement a Singleton class in java? How will this help?
An efficient way to sort patient files in an array of just 3 types 'High-importance', 'Mid-importance', 'Low-importance' which are in an arbitrary order (unsorted).
The output preference should start with the highest.
1. High-importance
2. Mid-importance
3. Low-importance
[high,low,low,med,high,low]
ps I was told to take advantage of the fact that they are just only 3 types.
given a pre and post order kindof a traversal (2 arrays) create an n-ary treee out of it with struct of the form :
struct node {
int data;
struct node *child[MAX];
int child_num;
}
given matrix like :
a b e d
b c f e
a b d d
….
find the longest path of consecutive alphabets given a starting alphabet. You can move in all 8 directions. for eg. a->b(right)->c(down)->d(diagnal down)… len = 4 , find max such len
There is an integer INPUT array {1,2,3,4,5}. Create an OUTPUT array such that each element in output array consists Product of all elements in INPUT array divided by element at that point. But you have to do it without using divide operator (/).
e.g
intput={1,2,3,4,5}
output[0]=(1*2*3*4*5)/1
output[1]=(1*2*3*4*5)/2 and so on.
Don't use divide operator
If problem Statement "sun is rise in west " !
?
How to do tester test it ? What are all possible solution ?
Suppose you are a stock trader and you can do as many trades but if you stop you can't do another trade. You can start with any trade. Given an array of profits/loss of trades and find the maximum profit you can make.
Input:
Number of trades
Profit/loss in each trade
Output:
Max Profit
Ex:
Input:
7
1 2 3 4 -2 -3 1Output:
10Explaination: Trade of [1,2,3,4]
Input:
5
-2 -3 -4 1 2Output:
3P.S: Any solution than Brute-Force.
The latest reality show has hit the TV: “Cat vs. Dog”. In this show, a bunch of cats and dogs compete for the very prestigious Best Pet Ever title. In each episode, the cats and dogs get to show themselves off, after which the viewers vote on which pets should stay and which should be forced to leave the show.
Each viewer gets to cast a vote on two things: one pet which should be kept on the show, and one pet which should be thrown out. Also, based on the universal fact that everyone is either a cat lover (i.e. a dog hater) or a dog lover (i.e. a cat hater), it has been decided that each vote must name exactly one cat and exactly one dog.
Ingenious as they are, the producers have decided to use an advancement procedure which guarantees that as many viewers as possible will continue watching the show: the pets that get to stay will be chosen so as to maximize the number of viewers who get both their opinions satisfied. Write a program to calculate this maximum number of viewers.
Input
On the first line one positive number: the number of testcases, at most 100. After that per testcase:
One line with three integers c, d, v (1 ≤ c, d ≤ 100 and 0 ≤ v ≤ 500): the number of cats, dogs, and voters.
v lines with two pet identifiers each. The first is the pet that this voter wants to keep, the second is the pet that this voter wants to throw out. A pet identifier starts with one of the characters ‘C’ or ‘D’, indicating whether the pet is a cat or dog, respectively. The remaining part of the identifier is an integer giving the number of the pet (between 1 and c for cats, and between 1 and d for dogs). So for instance, “D42” indicates dog number 42.
Output
Per testcase:
One line with the maximum possible number of satisfied voters for the show.
Sample Input 1
2
1 1 2
C1 D1
D1 C1
1 2 4
C1 D1
C1 D1
C1 D2
D2 C1
Sample Output 1
1
3
given a vector of integers, v[i] represent the stock price on day i. Now you may do at most K transactions. you must sell your stock before you buy it again and that means you can NOT have two stocks at the same time. write a program to find max profit you can get.
20
/ \
8 22
/ \ / \
5 3 4 25
/ \
10 14
traverse this binary tree vertically and its output will be
5
8 10
20 3 4
22 14
25
Given a staircase that has 'n' step, and you climb the staircase by jumping over the steps. You can cover at max of 'k' steps in a single jump. List all the possible sequence of jumps you could take to climb the staircase.
input:
n=4, k=2
output:
1,1,1,1
1,1,2
1,2,1
2,1,1
2,2
A Matrix of 1s and 0s is given, all zeros are water and 1s are land, first find out the number of ponds in the array (Reverse of islands problem). If one change can convert 1s in to zero then find out minimum number of changes that we need to make so that there will be only one pond in matrix..
Any algo how to make 1 pond ?
There is a code with a runtime error. We add printf to display the value of a variable and we don't get the runtime error anymore. explain what the reason can be.
Describe what’s incorrect about the following function and how you would fix the problems.typedef map< int, char *> List;void foo(){ List l; FILE *f = fopen("data.txt", "r"); if (f) { char line[100]; for (int i = 0; fgets(line, sizeof(line), f); ++i) { l[i] = new char[strlen(line)]; strcpy(l[i], line); } } for (List::const_iterator it = l.begin(); it != l.end(); ++it) { printf("%d: %s", it->first, it->second); }}
The function bar crashes when invoked. What is wrong and how would you fix the problem without changing anything in function bar?struct A { char *name; A() : name(NULL) { } ~A() { if (name) delete[] name; }};void bar(){ A x; x.name = new char[10]; strcpy(x.name, "John"); A y = x;}
The structure Info stores information of a person. Using a STL map, implement a collection of Info. The fields first and last must be used a unique, composite key. The list should be sorted by last, first in ascending order.typedef struct { string first, last; int age; string addr1, addr2;} Info;Also Using the map of Info from the question, output the list in reverse order. You may not define a new map or redefine the map you defined in the last question.
There is a list of rectangles and a list of points in a 2d space. Note that the edge of each rectangle are aligned to XY axis. question is how to find rectangles with point or points inside
Given two integer arrays A and B.
B contains exactly same numbers as A except two additional numbers. Find the two elements with minimum time and space complexity.
for ex: A ={1, 4, 2, 6, 3}
B = {4, 0,7, 6, 3, 2, 1}
ans: 0 7
I came with this solution:
Arrays.sort(A);
Arrays.sort(B);
int i=0, j=0;
while(j<=i+2 || i<A.length){
if(A[i]==B[j]){
++i;
++j}
else{
System.out.println(b[j]);
j++;
}
}
if(j==A.length+1){
System.out.println(B[j++]+" "B[j]);
}
if(j==B.length)
System.out.println)(B[j]);How will you dictionary sort integers without converting them to strings.
For ex: 1 2 10 20 100 110
Ans: 1 10 100 110 2 20.
A credit card company allows merchants to use their Point-of-sale (POS) terminal to accept payments. It wishes to charge merchants for every transaction that happens through thier POS terminal. Here are some charging rules that it has come up with:
Transactions are charged 2.0% of transaction amount if amount is less than 5000.00
Transactions are charged 1.5% of transaction amount if amount is between 5000.00 and 9999.99 (both inclusive)
Transactions are charged 1.0% of transaction amount if amount is equal to or above 10000.00
If merchant has already done transactions worth 50000.00 in a month, then rest of transactions of that month are charged at 0.5%
Every Month - two transactions of amount less than or equal to Rs. 5000.00 are free
Charges are rounded to nearest higher Rupee (Eg: 9.23 is rounded to 10.00)
Please develop a program to compute the charges for given inputs.
Your input will be in the following format. First Line: number of records follows, say N Next N Lines - Transaction data in the order - Transaction Date, Merchant Name, Amount
15
2014-06-25,XYZ Retail,10000.00
2014-07-01,XYZ Retail,10000.00
2014-07-01,ABC Retail,1000.00
2014-07-02,ABC Retail,3999.00
2014-07-02,ABC Retail,2000.00
2014-07-03,ABC Retail,10000.00
2014-07-15,ABC Retail,6530.00
2014-07-15,XYZ Retail,500.00
2014-07-18,ABC Retail,9750.00
2014-07-18,XYZ Retail,35000.00
2014-07-18,XYZ Retail,500.00
2014-07-18,XYZ Retail,5000.00
2014-07-18,XYZ Retail,5000.00
2014-08-02,XYZ Retail,10000.00
2014-08-02,XYZ Retail,1000.00
Transactions must be read and processed in the order given, else output will not match. Do not try to sort the transactions.
Output (Charges for each transaction on separate line)
100.00
100.00
0.00
0.00
40.00
100.00
98.00
0.00
147.00
350.00
0.00
75.00
25.00
100.00
0.00
Sample Input (Plaintext Link)
15
2014-06-25,XYZ Retail,10000.00
2014-07-01,XYZ Retail,10000.00
2014-07-01,ABC Retail,1000.00
2014-07-02,ABC Retail,3999.00
2014-07-02,ABC Retail,2000.00
2014-07-03,ABC Retail,10000.00
2014-07-15,ABC Retail,6530.00
2014-07-15,XYZ Retail,500.00
2014-07-18,ABC Retail,9750.00
2014-07-18,XYZ Retail,35000.00
2014-07-18,XYZ Retail,500.00
2014-07-18,XYZ Retail,5000.00
2014-07-18,XYZ Retail,5000.00
2014-08-02,XYZ Retail,10000.00
2014-08-02,XYZ Retail,1000.00
Sample Output (Plaintext Link)
100.00
100.00
0.00
0.00
40.00
100.00
98.00
0.00
147.00
350.00
0.00
75.00
25.00
100.00
0.00
Explanation
100.00 // Rule 3 applied
100.00 // Rule 3 applied
0.00 // Rule 5 applied (ABC Retail) for the month of July
0.00 // Rule 5 applied (ABC Retail) for the month of July
40.00 //Rule 1 & 6 applied
100.00 // Rule 3 applied
98.00 // Rule 2 & 6 applied
0.00 // Rule 5 applied (XYZ Retail) for the month of July
147.00 // Rule 2 & 6 applied
350.00 //Rule 3 applied
0.00 // Rule 5 applied (XYZ Retail) for the month of July
75.00 // Rule 2 applied
25.00 // Rule 4 applied
100.00 // Rule 3 applied
0.00 // Rule 5 applied (XYZ retail) - for the month of Augus
Given a list of strings, return a list of lists of strings that groups all anagrams.
Ex. given {trees, bike, cars, steer, arcs}
return { {cars, arcs}, {bike}, {trees, steer} }
m = # of words
n = length of longest word
I solved this in O(m * n * log n) time.
//Given a method that takes in a positive non-zero number N, return from that method the total number of factors of N. //Start with O(n) solution and make it faster if we have time
You have a chess board of size NxN. You have a horse at a given starting position. You also have a function that gives you all the positions that the horse can reach from it's current position.
Given an ending position, find the path to it that uses the minimum number of moves.
Implement the divide of two integers without using the divide operator.
After implementing the O(n) algorithm to subtract the divisor from the divider, he asked me to implement a better algorithm.
I started working towards bit manipulation, but ran out of time.
He also hinted that I could have used binary search. Not sure how though.
Given a stack of magazines create an anonymous love note (pick words or alphabets from the magazine and create the note)...
He gave me the choice of handling words or alphabets
Assume you have a scanned copy of the magazine as a string.
Once I implemented both words and alphabets, he asked me to scale it to mass production and maximize the throughput of a fulfillment center handling this
Design a robot that will take your order and make sandwiches for you.
Once I was done with this, I was supposed to extend it to have multiple robots doing this job like an assembly line handling multiple sandwiches and other edible items
Once I handled that, he asked me to create a web service for this that will handle online ordering. He also wanted me to implement fulfillment centers
Give a tree (any tree, can be a binary. I told the interviewer that I assume it is binary tree and he said that is fine). Print the tree content on the screen one tree level per line
i.e.
if a tree is like this:
a
/ \
b c
/ /
e f
The output would be
a
bc
ef
Too bad, I was only able to make it print on one line instead of separate line. Until after the interview is over. Then I figure the final answer.
Write code/ logic to count number of words in a string delimited by " ". Anything apart form " " are ignore for the counting. String could be very big as big as 5 GB of data. So add logic to handle such large strings..
ex: aaa b c ddd e = Count (5)
aaaaaaaaaaa = Count(1)
a
b
c
d
Count(1) as there are no spaces rather carriage returns are found.
PS: In case above question is not clear do let me know.
public class Base Test {
protected void finalize() {
System.out.println("Destroying Base");
}
}
public class DerivedTest extends Base Test{
protected void finalize() {
System.out.println("Destroying Derived");
}
}
What is output when an instance of DerivedTest is finalized?
implement database structure in Java (that would be multithreaded)
I was at a job interview and the intreviewer gave me a task: I have an object called DBconn. that Object has 4 methods:
• connect(Params)
• query(String)
• update (String)
• disconnect()
My mission was to implement that Database object (DBconn) in a singelton pattern - meaning the first person who create this object will get a new instance of it and from there one - every person will get that instance of the databse (not to create a new instance for every user - but share the same object).
I first tried to us the standard way of singelton where I create a DBconn object in the first time that a user called it - and return the instance from there on. The problem was that the connect method should only run for the first time (meaning user1 connect, and then user 2 also connect - is not valid) and if I return the databse every user that want to harm to system can conncect or diconnect as he please.
So i decided to return the singelton class (instead of the database object), and do the "connect" only for the first user. But then I encounter a diffrente problem: the query and update methods of the DBconn should work in multythread way (meaning they are synchornized - according to DBconn implemetion). But if I write them in a synchronized java method that will force the program to excute each of them speratly (because of the "synchronized" saved word) and that will ignore the beauty multythreaded way that "update" and "query" work.
So he gave me a homework task (which ovcourse inclueded using the internet and counslting) - to try and solve this problem by writing it in java.
this is what I did so far (I also tried to implememts a very raw database which saves persons data) but I still don't know how to make the update and query to: 1. work in a muiltythread way. 2. work in a muiltythread way in the singelton class as well
Thanks for all of you who trying to help:
SingeltonDB:
public class SingeltonDB {
private static DBconnImpl db = null;
private static SingeltonDB singalDb = null;
private SingeltonDB(String username, String password) {
db = new DBconnImpl();
}
public static boolean isOpen() {
return (db != null);
}
public synchronized static SingeltonDB getInstance(String username,
String password) throws Exception {
if (db != null) {
} else {
System.out.println("The database is now open");
singalDb = new SingeltonDB(username, password);
}
db.connect(username, password);
System.out.println("The database was connected");
return singalDb;
}
public synchronized static SingeltonDB getInstance() throws Exception {
if (db == null) {
throw (new Exception("The database is not open"));
}
return singalDb;
}
public void create(String tableName) throws Exception {
db.create(tableName);
}
public User query(String tableName, int rowID) throws Exception {
if (db == null) {
System.out.println("Error: the database is not open");
return null;
}
return (db.query(tableName, rowID));
}
public void update(String tableName, User user) throws Exception {
if (db == null) {
System.out.println("Error: the database is not open");
return;
}
db.update(tableName, user);
}
}DBconnImpl:
import java.util.*;
public class DBconnImpl {
private Map<String, Table> tables;
private boolean connected;
private String username;
private String password;
public DBconnImpl() {
tables = new HashMap<>();
this.username = "MyAccount";
this.password = "123";
connected = false;
}
public boolean connect(String username, String password) throws Exception {
if (connected) {
throw (new Exception("Error: The database is already opened."));
}
if (!this.username.equals(username) || !this.password.equals(password)) {
System.out.println("wrong username or password.");
return false;
}
connected = true;
return true;
}
public void create(String tableName) throws Exception {
if (!connected) {
throw (new Exception("Error: The database is not opened."));
}
tables.put(tableName, new Table(tableName));
}
public User query(String tableName, int rowID) throws Exception {
if (!connected) {
throw (new Exception("Error: The database is not opened."));
}
return (tables.get(tableName).query(rowID));
}
public void update(String tableName, User user) throws Exception {
if (!connected) {
throw (new Exception("Error: The database is not opened."));
}
tables.get(tableName).update(user);
}
public boolean disconnect() throws Exception {
if (!connected) {
throw (new Exception("Error: The database is not opened."));
}
connected = false;
return true;
}
}Table
import java.util.*;
public class Table {
private Map<Integer, User> table;
public Table(String tableName) {
table = new HashMap<>();
}
public User query(int id) throws Exception {
return table.get(id);
}
public void update(User user) throws Exception {
table.put(user.getId(), user);
System.out.println("The user " + user.getName()
+ " was successfully entered in the with ID number "
+ user.getId() + ".");
}
}User
public class User {
private String name;
private int id;
private int age;
public User(int id, String name, int age) {
this.name = name;
this.age = age;
this.id = id;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public int getId() {
return id;
}
@Override
public String toString() {
return ("(" + name + " , " + age + ")");
}
}UserContorller
public class UserContorller {
SingeltonDB db;
public UserContorller(String user, String pass) throws Exception {
if (!SingeltonDB.isOpen()) {
db = SingeltonDB.getInstance(user, pass);
} else {
System.out.println("dataBase already opened");
}
}
public UserContorller() throws Exception {
if (SingeltonDB.isOpen()) {
db = SingeltonDB.getInstance();
} else {
System.out.println("dataBase not opened");
}
}
public void createTable(String table) throws Exception {
db.create(table);
}
public void saveUser(String table, int id, String name, int age)
throws Exception {
db.update(table, new User(id, name, age));
}
public User getUser(String table, int id) throws Exception {
return db.query(table, id);
}
}Main
public class Main {
public static void main(String[] args) throws Exception {
UserContorller uc1 = new UserContorller("MyAccount", "123");
UserContorller uc2 = new UserContorller();
UserContorller uc3 = new UserContorller();
uc1.createTable("table1");
uc2.saveUser("table1", 1, "David", 10);
System.out.println(uc3.getUser("table1", 1));
}
}A batch of time intervals like {2/3-2/20, 2,6-3/5}. need to split the intervals to{2/3-2/6, 2/7-2/20, 2/21-3/5}. Solve it with minimum time complexity. How to do it?
An abbreviation of a word is <first letter><length -2 of the word><last letter>. Giving a dictionary and a word, find whether there is another word with same abbreviation in the dictionary.
"internationalization" -> "i18n"
"localization" -> "l10n"
“dog” -> “d1g”
“accessibility”, “automatically” -> “a11y”
Input: dictionary, word
Output: boolean: is the abbreviation of the word unique w.r.t. the dictionary?
Given two input string check if anyone is substring of other.
example aaaaaabbb, aaaabbb
return true
PS: Don't use any internal string library :)
Given a 2^31 x 2^31 tic tac toe board, describe how you would store the state of the game to check if there is a winner.
Given this math equation, what is the value of x and y?
x+y = 7
x^2+y^2 = 29
This was asked by one of the interviewers to my friend.
what about further generalizing this to:
x+y = 7
x^2+y^2 = 29
x^3+y^3 = 133
so on until k?
Reverse last 5 nodes of linkedlist. Please let me know if there is any better way.
E.g.
Input: 1,2,3,4,5,6,7
Output: 1,2,7,6,5,4,3
package com.acct;
public class SinglyLinkedListReverseLast5 {
public static void main(String[] args) {
Node n7 = new Node(7, null);
Node n6 = new Node(6, n7);
Node n5 = new Node(5, n6);
Node n4 = new Node(4, n5);
Node n3 = new Node(3, n4);
Node n2 = new Node(2, n3);
Node n1 = new Node(1, n2);
int numberOfNodestoReverse = 5;
System.out.println(n1.toString());
reverse(getNthElement(n1, numberOfNodestoReverse+1));
System.out.println(n1.toString());
}
public static Node getNthElement(Node head, int n) {
Node f_ptr = head;
Node s_ptr = head;
for (; n > 0; n--) {
f_ptr = f_ptr.next;
}
while (f_ptr != null) {
f_ptr = f_ptr.next;
s_ptr = s_ptr.next;
}
System.out.println(s_ptr.toString());
return s_ptr;
}
public static void reverse(Node head) {
Node current = null;
Node next;
Node first = head;
head = head.next;
while (head != null) {
next = head.next;
head.next = current;
current = head;
head = next;
}
first.next = current;
}
}
class Node {
int value;
Node next;
Node(int value, Node next) {
this.value = value;
this.next = next;
}
public String toString() {
String result = value + " ";
if (next != null) {
result += next.toString();
}
return result;
}
}A server receives requests from different clients...each client send a Runnable job and time on which this job should be run. Write a java program that would accept these jobs and run each job at the required time. Hint: the solution should have a job priority queue to hold the jobs and it should be multithreaded. One thread should accept the tasks, the other one should run the jobs. Also conditions and signalling will be used
Given a array of positive integers, you have to find the smallest positive integer that can not be formed from the sum of numbers from array.
Given a custom table (id, ...), an order table (id, order_date, custom_fk, ...) and an order item table (id, order_fk, price, sale_price...) where price is "not null" and sale_price isn't, write a SQL query statement to find out customers' total purchasing payment in the past six months.
Given a custom table (id, ...), an order table (id, order_date, custom_fk, ...) and an order item table (id, order_fk, ...), write a SQL query statement to find out all customers who haven't placed any order in the past six months.
Given an array containing both positive and negative integers, return an array of alternating positive integers and negative integers such that each set of integers--e.g all the positive integers and all the negative integers are in the same order as in the input array. For example, input {2, 3, -4, -9, -1, -7, 1, -5, -6} and its output shall be {2, -4, 3, -9, 1, -1, -7, -5, -6}. Can you implement it without using any additional space? Also, provide your test cases.
Given an array of integers, find the closest pair with a sum which equals to a given integer. For example, for {1, 7, 5, 3, 9} and 10. The pair is {7, 3}. Also, provide test cases.
Suppose that there is a database table, and four processes read the table at the same time. But, only one process is allowed to read the same row of the table at the same time. How do you enforce the exclusive-read on a row?
What is Encapsulation? What is inheritance? When and Why should you use the inheritance?
What is the Abstract class? What is the difference between an abstract class and an interface? When should you use an abstract class instead of interface?
Suppose that Amazon web site has two data tables: One is the customer table. The other is the order table. How do you find the customers who never order anything?
an bacteria grows at the speed that it will double its volume per minute. If you put it in a jar, it will fill the jar in one hour. how long will it take to fill a half of the jar?
A binary tree represent an organization hierarchy. The root node is the CEO and etc. design a algorithm to print the tree level by level.
Given an integer array, adjust each integers so that the difference of every adjcent integers are not greater than a given number target.
If the array before adjustment is A, the array after adjustment is B, you should minimize the sum of |A[i]-B[i]|
You can assume each number in the array is a positive integer and not greater than 100
Given [1,4,2,3] and target=1, one of the solutions is [2,3,2,3], the adjustment cost is 2 and it's minimal. Return 2.
Given an integer array, adjust each integers so that the difference of every adjacent integers are not greater than a given number target.
If the array before adjustment is A, the array after adjustment is B, you should minimize the sum of |A[i]-B[i]|
You can assume each number in the array is a positive integer and not greater than 100
Given [1,4,2,3] and target=1, one of the solutions is [2,3,2,3], the adjustment cost is 2 and it's minimal. Return 2.
Given an array A and an array B. Sort all the elements of A in the order of B. Sort the remaining elements.
e.g.
A = {4,2,7,6,8,9,1,3,2,5,6}
B = {6,3,4,1}
Output= {6,6,3,4,1,2,3,5,7,8,9}
Check if 2 link lists merge or not. If yes, return the 1st common node.
Check if an integer is a power of 2 or not.
Given n number of legacy services with user data<userid, info, date>
Design an API to return user data in a given date range, it should collect data from each service and merge and return the data sorted by date.
singly link list
substring
substring
map
array
Describe Class diagram of a Card Game like Poker. What classes to be used. How to deal and shuffle the cards in cards class
Array of size (n-m) with numbers from 1..n with m of them missing. Find one all of the missing numbers in O(log). Array is sorted.
Example:
n = 8
arr = [1,2,4,5,6,8]
m=2
Result has to be a set {3, 7}.
Give you a list of Modules of Dependencies,
A --> B,C
B --> D,E,F
D --> F
And please return back a correct build order of Module (input)
Shorten a List of Strings.
Design a Black-Jack poker game
Give an 2d-characters Grid, char[][] A, and a dictionary, List<String> dict. Search all possible words in the 2d-Grid.
Take a list of integers (left to right order) and return an integer of the number of identical binary trees that can be created from the same list.
Input: [10, 8, 15, 6, 9, 4, 5]
Output: 24
Input: [12, 6, 19, 15, 5]
Output: 6
Input: [44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64]
Output: 1
I wrote a brute-force 'solution', creating a binary tree for each permutation of the list (with the same root as Input list) and compared each to the binary tree from the Input list. For large input lists (length > 10), my 'solution' is way too slow.
Take a list of integers (left to right order) and return an integer of the number of identical binary trees that can be created from the same list.
Input: [10, 8, 15, 6, 9, 4, 5]
Output: 24
Input: [12, 6, 19, 15, 5]
Output: 6
Input: [44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64]
Output: 1
I wrote a brute-force 'solution', creating a binary tree for each permutation of the list (with the same root as Input list) and compared each to the binary tree from the Input list. For large input lists (length > 10), my 'solution' is useless.
You have a class that many libraries depend on. You need to modify the class for one application. Which of the following changes require recompiling all libraries before it is safe to build the application?
a. add a constructor
b. add a data member
c. change destructor into virtual
d. add an argument with default value to an existing member function
Do thread join without join function?
Given a BST, how would you return the kth smallest element. Cover all the corner cases with time complexity logn
Write a program that reverses alternate elements in a given linked list input: a->b->c->d, output should be b->a->d->c
You have just earned $500 voucher to spend at any restaurant. However,
since you are a programmer and a foodie you want to maximize how you
allocate your money.
Attached is CSV that has a list of:
-Beverages
-Appetizers
-Entrees
-Desserts
-Restaurants
The CSV file looks something like
Beverage Name,Beverage Cost,Beverage Value,Appetizer Name,Appetizer Cost,Appetizer Value,Entrée Name,Entrée Cost,Entrée Value,Desert Name,Desert Cost,Desert Value,Restaurant Name,Restaurant Drink Cost,Restaurant Value
7up, $92.00 ,32,Fresh Rolls, $82.00 ,30,Fried Rice, $78.00 ,29,Vanilla Ice Cream, $76.00 ,13,Applebee's, $43.00 ,19
Sprite, $89.00 ,24,Spring Rolls, $54.00 ,18,PB & J, $49.00 ,29,chocolate cake, $50.00 ,25,Arby's, $26.00 ,5
Next to each item there is a cost and a perceived value.
Your job is to construct a meal under your budget of $500 that includes:
1 Beverage
3 Appetizers
2 Entrees
1 Dessert
1 Flex Option (This can be an Appetizer, Entree, or Desert)
1 Restaurant
1. Please list the 25 Combinations with the highest perceived value
given your budget
2. Please list the 25 Combinations with the lowest perceived value
given your budget.
Make sure your program assumes that the number of items in each
category is N
The problem I am having is using the knapsack algorithm in this case, especially with item constraints. The problem seems to be poorly written.
public static void main(String[] args) throws IOException {
File file = new File("Menu.csv");
List<String> lines = Files.readAllLines(file.toPath(),
StandardCharsets.UTF_8);
List<Beverage> beverages = new ArrayList<>();
List<Appetizer> appetizers = new ArrayList<>();
List<Entree> entrees = new ArrayList<>();
List<Dessert> desserts = new ArrayList<>();
List<RestaurantDrink> restaurantDrinks = new ArrayList<>();
boolean firstLine = true;
for (String line : lines) {
if (firstLine)
{
firstLine = false;
continue; //don't care about first line
}
String[] array = line.split(",");
int j = 0;
Beverage b = new Beverage();
Appetizer app = new Appetizer();
Entree e = new Entree();
Dessert d = new Dessert();
RestaurantDrink rd = new RestaurantDrink();
for (String a : array) {
switch (j)
{
case 0:
if (!a.equals("")) //nothing
{
b.name = a;
}
break;
case 1:
if (!a.equals("")) //nothing
{
b.cost = Double.parseDouble(a.replace("$", ""));
}
break;
case 2:
if (!a.equals("")) //nothing
{
b.perceivedValue = Integer.parseInt(a);
beverages.add(b);
}
break;
case 3:
app.name = a;
break;
case 4:
app.cost = Double.parseDouble(a.replace("$", ""));
break;
case 5:
app.perceivedValue = Integer.parseInt(a);
appetizers.add(app);
break;
case 6:
e.name = a;
break;
case 7:
e.cost = Double.parseDouble(a.replace("$", ""));
break;
case 8:
e.perceivedValue = Integer.parseInt(a);
entrees.add(e);
break;
case 9:
d.name = a;
break;
case 10:
if (a.equals("")) //free dessert
{
d.cost = 0.00;
} else {
d.cost = Double.parseDouble(a.replace("$", ""));
}
break;
case 11:
if (a.equals("")) //free dessert
{
d.perceivedValue = 0;
} else {
d.perceivedValue = Integer.parseInt(a);
}
desserts.add(d);
break;
case 12:
rd.name = a;
break;
case 13:
if (a.equals("")) //free restaurant drink
{
rd.cost = 0.00;
} else {
rd.cost = Double.parseDouble(a.replace("$", ""));
}
break;
case 14:
if (a.equals("")) //free dessert
{
rd.perceivedValue = 0;
} else {
rd.perceivedValue = Integer.parseInt(a);
}
restaurantDrinks.add(rd);
break;
}
j++;
}
j = 0;
}
}is all I got. I'm just having trouble with the knapsack portion.
how to sent buffer limit in BufferedReader/ BufferedWriter class
How to implement thread safety in java without using synchronized method?
Given a set of busy time intervals of two people as in a calendar, find the free time intervals of both the people so as to arrange a new meeting
input: increasing sequence of pair of numbers
per1: (1,5) (10, 14) (19,20) (21,24) (27,30)
per2: (3,5) (12,15) (18, 21) (23, 24)
ouput: (6,9) (16,17) (22,22) (25,26)
How to classify 3 classes using each MICD and MED classifiers using Matlab ?
Given two strings. Figure out if 2nd one is substring of 1st one. 2nd may contain wildcard characters like '*','?' etc
Write a recursive function to print directory structure. Two function were given isfolder() and openfolder().
What data structures will you use to implement a text editor. Size of editor can be changed and you also need to save the styling information for all the text like italic, bold etc.
finds a domino pattern for a "double-N" domino set that forms a loop / a ring using all available tiles.
for example,In a double-two domino set, with six tiles, (0 , 0) (0 , 1) (1 , 1) (1 , 2) (2 , 2) (2 , 0). So if parameter is 2, the function should return true. if no loop found, should return false.
Dominoes are small rectangular game tiles divided into two squares and embossed with dots on the top surface of the tile. You can think of dots as integers. A double-N domino set consists of (N+1)(N+2)/2 tiles, e.g. a standard double-six domino set has 28 tiles (T): one for each possible pair of values from (0.0) to (6.6) - no pair of numbers occurs more than once.
You are given an array of non-negative integers (0, 1, 2 etc). The value in each element represents the number of hops you may take to the next destination. Write a function that determines when you start from the first element whether you will be able to reach the last element of the array.
if a value is 3, you can take either 0, 1, 2 or 3 hops.
For eg: for the array with elements 1, 2, 0, 1, 0, 1, any route you take from the first element, you will not be able to reach the last element.
you have 2 lists of points
- for one point in the first list, you have to find all the points in the second list that are in a certain radius with a fast algorithm
Input a matrics, print the elements one by one:right->left down->left->up. The 1st line is the matrics size, then follows the matrics elements. Ex:
5 3
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
First loop:
starts from the top left '1';
1: to right, print 1,2,3,4,5
2: to left down, print 9,13
3: to left, print 12,11
4: to up, print 6 ('1' has been print, ignore)
Second round:
1: to right, print 7,8
2: no more elements to print
So the elements should be:
1,2,3,4,5,9,13,12,11,6,7,8
We have a class as follows:
public class People{
String name;
String position;
String sex;
...
...
public String getAttribute(String attrName){
/**
* This is a generic getter method that will give you
* any attribute value based on the passed attribute
* Name;
* for eg: getAttribute("name") => will return the
* attriute(Name) value of the current object.
*/
}
}I now give you two List:
list1<People> friends;
list2<String> attributes;
Using the generic getter method, we have to group "friends" on "attributes". Think of this as an implementation of GROUP BY function to be implemented on objects in list1 and to be grouped on entries in list2.
eg: list2 = {sex, occupation}
So objects in list1 will be grouped such that all Male-doctors together, Female-cops together, male-cops together, etc.
you have numbers between 1 to n. a set of number i.e. (4,5) means that person number 4 is connected to person number 5. find all the ways the a group of n pepole can be connected. i.e. for 0 and 1 there is the empty set, for 2 there is 2 ways, empty set and {1,2} only for 3 there are 4 ways: {}, {(1,2)} {(2,3)}, {(3,1)} for 4 there are 10 ways ({},{(1,2)}, {(1,2),(3,4)},.......
you can do it by factorial and cobination but there is another way that state that:
T(n)=T(n-1) + (n-1)*T(n-2)
(while T(n) is the function that computes the number of ways..
Can someone explain why this equation is true?
you have a numbers between 1 to n. a set of number i.e. (4,5) means that person number 4 is connected to person number 5. find all the ways the a group of n pepole can be connected. i.e. for 0 and 1 there is the empty set, for 2 there is 2 ways, empty set and {1,2} only for 3 there are 4 ways: {}, {(1,2)} {(2,3)}, {(3,1)}
for 4 there are 10 ways ({},{(1,2)}, {(1,2),(3,4)},.......
you can do it by factorial and cobination but there is another way that state that:
T(n)=T(n-1) + (n-1)*T(n-2)
(while T(n) is the function that computes the number of ways..
can someone explain why this equation is true?
Thanks...
Chinese chess has 8*8=64 cells.And the point is (1,1),(1,2),..............(8,8).And the horse walks by diagonal line of two cells from where point it is.Calculate the shortest step(s) between two points for the horse to walk. Eg. (1,1) to (4,4). Horse go like this (1,1)>(2,3)>(4,4)
Chinese chess has 8*8=64 cells.And the point is (1,1),(1,2),..............(8,8).And the horse walks by diagonal line of two cells.Calculate the shortest step(s) between two points for the horse to walk. Eg. (1,1) to (4,4). Horse go like this (1,1)>(2,3)>(4,4)
Jumper Game: A NxN grid which contains either of 0-empty, 1 - player 1, 2 - player 2. Given a position in the grid, find the longest jump path. For jump path, you can jump only diagonally, you can jump on opponent cell and also the landing cell should be empty. No opponent cell can be jumped more than once. Write a function which takes grid and a specific position in the grid, and returns the longest possible number of jumps in the grid. For Example:
if grid = {
{ 0,0,0,0,0,0 },
{ 0,1,0,0,0,0 },
{ 2,0,2,0,2,0 },
{ 0,0,0,0,0,0 },
{ 0,0,0,0,0,0 },
{ 0,0,0,0,0,0 },
};
Answer should be 2 - (1,1) -> (3,3) -> (1,5)Given an array of integers.
Move all non-zero elements to the left of all zero elements.
There's a new language which uses the latin alphabet. However, you don't know the order among letters.
It could be:
a b c d ...
as it could also be:
b e z a m i ...
You receive a list of words lexicographically sorted by the rules of this new language. From this list, derive one valid particular ordering of letters in this language.
There are different buildings standing close to each other. These are of same width but different height.
Suppose if rainfall happens, what will be the volume of water that get trapped on top of all these buildings together. ?
INPUT (Example)
No: of buildings : 4
heights of the buildings(in any units): 3 4 3 4
Design Maps: You have set of [lat, long] for all famous locations. Given your position [lat, long] return all famous locations within r radius of your position.
You have set of [lat, long] of all famous locations. Given your position [lat, long] return all famous locations within radius r of your position
-How to mitigate that your software is the real one and not the stolen one.
How to steal a password when i have both public key and know the algorithm?
If i record the traffic when i write the username and password and redirect my page?
Given a number,print it in words.
19621 -> One lakh ninety six thousand and twenty one.
Given a array of positive integers, find all possible triangle triplets that can be formed from this array.
eg: 9 8 10 7
ans: 9 8 10, 9 8 7, 9 10 7, 7 8 10
Note : array not sorted, there is no limit on the array length
Given an array of type:-
1. Increasing
2. Decreasing.
3. Increase-Decrease
4. Decrease-Increase
Find:- 1. Type of array in minimum steps ?
2. Maximum element from array in min steps?
Question was "Given a pattern and a string input - find if the string follows the same pattern and return 0 or 1.
Examples:
1) Pattern : "abba", input: "redbluebluered" should return 1.
2) Pattern: "aaaa", input: "asdasdasdasd" should return 1.
3) Pattern: "aabb", input: "xyzabcxzyabc" should return 0.
I can think of a brute-force solution for this question where we add the character in the pattern and n length of the string to a hashmap and recurse over the pattern array and string. But is there anything more efficient? This was a pretty difficult question in my opinion.
Given an array of integers when the difference between every two neighbored elements is either -1 or +1 or 0.
Write an efficient search algorithm to find a given number of x in the array.
Implement algo for ls command in unix. You have n ordered file names with you. You have to print file names in column then in rows.
e.g. I have 5 files
F1 F3 F5
F2 F4
Minimize on number of rows
Maximize on number of columns
Max Page Width possible P
Page width of any row = max width of all files in first column + max width of all files in second column + ... +max width of all files in last column
You are given an mxn grid, where (0,0) refers top most left position and (m-1,n-1) the bottom most right. The grid is filled with ones. All positions in the grid that are blocked are filled with zeros. You are given this grid and are assured that there exists atleast one path from (0,0) to (m-1, n-1). Find the minimum distance of the path from (0,0) to (m-1, n-1) given that you are allowed to move only vertically, horizontally and diagonallyYou have a set of N objects. Each of these objects have certain properties associated with them. A property is represented by a (key, value) pair. For example, assume you have the following two objects.
Tower:
{
(height, 100), (weight, 50),
(xposition, 25), (yposition, 36)
}
Tree:
{
(area, 100), (noofleaves, 500),
(height, 25), (yposition, 36)
}
Each object you have, will have at most 4 properties. An object will have at least 1 property. Note, from the two objects above, that it is not necessary for key in the properties to be same for all the objects. Also, it is not necessary for the key to be different.
Now, given N such objects, you wish to answer M queries. Each query is represented by a set of properties (again, at most 4 properties, and at least 1 property). The answer for the query is the number of objects in the set, that have all the given properties. Two properties are considered equal iff both the key and the value match.
For example, if you have the above two objects, then the answer for the following queries is
Query:
{ (height, 100), (yposition, 36) }
Answer:
1 // matches Tower, but not Tree
Query:
{ (yposition, 36) }
Answer:
2 // matches both Tower and Tree
Query:
{ (height, 100), (noofleaves, 500) }
Answer:
0 // neither Tower, not Tree satisfy both properties
Input
The first line of input contains N and M. This is followed by the description of the N objects. The description of the i-th object will start by a number k, which is the number of properties associated with the object. The next k lines contain two space separated strings - the property key and the property value. Note that the property value is not necessarily an integer (although this is so for the example above).
This is followed by the description of M queries. The format of a query will be exactly same to that of the objects. Check the Sample Input for clarification.
One test file will contain only one test case. A single test case may contain several queries.
Output
Print M lines. Each line must be the answer of the respective query.
Constraints
1 ≤ N ≤ 10000
1 ≤ M ≤ 100000
1 ≤ k ≤ 4
Sample Input
2 3
4
height 100a
weight 50b
xposition 25a
yposition 36b
4
area 100a
noofleaves 500
height 25
yposition 36b
3
weight 80
xposition 25a
yposition 36b
1
yposition 36b
2
xposition 25a
yposition 36b
Sample Output
0
2
1
You are given a rectangular grid with 2 rows and N columns. The top row is labeled 1 and the bottom row is labeled 2. The columns are labeled from 1 to N in increasing order. Each cell in the grid contains a single character.
Consider a hamiltonian walk in this grid. Meaning, pick a starting cell, say (i,j), and consider a path that starts from (i,j) and goes through every cell in the grid exactly once. Note that you can only walk to adjacent cells, or cells that you share a common edge with. There may be several such paths. Let us concatenate the characters in the order in which the cells are visited during a walk. The string formed can be called the string for the walk.
Among all the possible walks, and their respective strings, find out the lexicographically smallest string. We know that the length of the strings are all the same - to be precise, 2N. Thus, the lexicographically smallest string is simply the alphabetically smallest string if you compare the characters from left to right.
Input
The first line of input contains a number T, the number of test cases. Then follow T test cases. Each test case contains 3 lines. The first line contains the number N, the number of columns in the grid. It is well known of course that the grid contains 2 rows. The next two lines contain the description of the grid in the form of two strings; the string of N characters in row 1 from left to right and the string of N characters in row 2 from left to right, respectively. Each character will be a lowercase engish letter.
Output
Output a single line for each test case. The line must contain a string with 2N characters. This string should be the lexicographically smallest string for some hamiltonian walk in the grid.
Constraints
1 = T = 100
1 = N = 10
Sample Input
2
3
abc
def
10
ababaaabab
bababababa
Sample Output
abcfed
aaababababababababab
Explanation
In the first test the possible strings are { abcfed, adebcf, adefcb, badefc, bcfeda, cbadef, cfedab, cfebad, dabcfe, dabefc, defcba, edabcf, efcbad, fedabc, fcbade, fcbeda }. The smallest string is abcfed.
You have 81 balls. 80 balls have the same weight. 1 ball is the lightest one. What would be the minimum possible way to find the lightest ball ?
(Use Dynamic Programming)
There are multiple rooms in a floor. There are one or more fire exits. Each door can be designed with an option of pull or push. For fire safety, a door should be designed so as to open (push) towards the fire exit.
Design a data structure to represent the floor and door design. A person could start from any room and moves towards fire exit. Write an algorithm to check if all the doors are designed to be pushed towards fire exit.Given a large array of unsigned ints, quickly find two who's sum is 10
Then the interviewer asked me to write test cases.
Followed by how to implement this on a distributed system, where multiple systems can read/write simultaneously on a shared cache (HINT: It is ok if you do not return the first instance)
A seller sells lot of products in his store and people place orders,just like any other store. Each item has a different weight and price.
And each order can be a combination of different number of items with random quantity. Now each of these orders areto be put into different packages and sent to the courier company for delivery.
But there are certain rules while splitting items into packages, they are as below:
1. If the cost of all the items in an order is more than $1000, split those items into multiple
packages, otherwise one package would be enough.
2. If the items in the same order are split into multiple packages, then the weight of the
packages should be equally distributed over the packages with consideration of optimum
courier charges.
3. While splitting, NO PACKAGE can have a total price above $1000
In a city year of birth/death of people who where born and died between year 1900 to 2000 are given. Write an algorithm to find the year in which max people were alive.
What is the maximum number of edges you could add to n vertexes to make a acyclic undirected graph?
Follow up:
What is the maximum number of edges you could add to n vertexes to make a acyclic directed graph?
There is a string whose characters can only be either ‘a’, ‘b’ or ‘_’ (there can be only one ‘_’ in the string). At each step, we can modify the string as follows:
1. ‘_’ can be swapped with its adjacent character, example “a_ba” can be changed to either “_aba” or “ab_a”.
2. Two characters adjacent to ‘_’ (both on the same side of ‘_’) can be reversed along with the ‘_’ if both characters are different, example, “aa_ba” can be changed to “aaab_” but not to “_aaba” because both characters are ‘a’.
You are given two strings, the initial state and the final state (lengths will be same), you have to output the minimum number of steps required to change the string in initial state to the string in the final state.
example:
input: a_b ab_
output: 1
input: abaa_a b_aaaa
output: 4
reason for example 2:- abaa_a -> aba_aa -> ab_aaa -> _baaaa -> b_aaaa
Implement a vector-like data structure from scratch.
This question was to be done in C or C++.
Discussion topics:
1. Dealing with out of bounds accesses.
2. What happens when you need to increase the vector's size?
3. How many copies does the structure perform to insert n elements? That is, n calls to vector.push_back
You have a sorted array containing the age of every person on Earth.
[0, 0, 0, 0, ..., 1, 1, ..., 28, 28, ..., 110, ...]
Find out how many people have each age.
Design a queue (FIFO) structure using only stacks (LIFO).
Code is not necessary.
Follow-up: provide a complexity analysis of push and remove operations.
Write a program to find pattern.
0: 1
1: 11
2: 21
3: 1211
4: 111221
5: 312211
Iterate over the previous number, and find count for same number number. Append that count before number.
e.g.,
public String pattern(int input){}
If input = 4, function should return 111221.
Given a string S, you are allowed to convert it to a palindrome by adding 0 or more characters in front of it.
Find the length of the shortest palindrome that you can create from S by applying the above transformation.
I think it's one system design question. Design one google's API, qps (query per second).
Given two string you need to tell whether edit distance between two string is 1 or not.
Two sorted array of integer are given, you need to find nth rank element from combine array.
There is a set of n bolts and n nuts given. You have only API that tells whether given nut is smaller or larger then for a bolt no any other relative number. You need to match all nuts and bolts in O(nlogn).
Given an abstract class A having a function sumBill(int a, int b). Now assume that you have 3 or 4 class extending class A and implementing their version of sumBill. And in various locations in the code you are making calls to sumBill with integer parameters.
Later on it is identified that the parameters need to be of type double rather than int. So now one has to go refactor all the places which make a call to sumBill to pass parameters of double data type.
So the question is what could the developer had done better to avoid such a problem in the first place.
Its a design pattern question.
Minesweeper question: Given an n x m grid holding individual mine co-ordinates, identify all of the mine clusters. A mine cluster is the largest collection of neighboring mines.
Example input:
0 1 2 3
---------
0|0|1|0|1
1|0|0|1|1
2|0|0|0|0
3|1|1|0|0
Expected output:
[cluster 1] (0,1),(1,2),(1,3),(0,3)
[cluster 2] (3,0),(3,1)
Let's say there is a double square number X, which can be expressed as the sum of two perfect squares, for example, 10 is double square because 10 = 3^2 + 1^2
Determine the number of ways which it can be written as the sum of two squares
6
/ \
3 5
/ \ \
2 5 4
/ \
7 4There are 4 leaves, hence 4 root to leaf paths:
Path Sum
6->3->2 632
6->3->5->7 6357
6->3->5->4 6354
6->5>4 654
Answer: 632+6357+6354+654=13997
6
/ \
3 5
/ \ \
2 5 4
/ \
7 4
There are 4 leaves, hence 4 root to leaf paths:
Path Sum
6->3->2 632
6->3->5->7 6357
6->3->5->4 6354
6->5>4 654
Answer = 632 + 6357 + 6354 + 654 = 13997
Write a program to make the following possible with any given tree.
6
/ \
3 5
/ \ \
2 5 4
/ \
7 4
There are 4 leaves, hence 4 root to leaf paths:
Path Sum
6->3->2 632
6->3->5->7 6357
6->3->5->4 6354
6->5>4 654
Answer = 632 + 6357 + 6354 + 654 = 13997
Suggest a Data Structure to do the following opperations with time complexity O(1).
insert(int element); //insertes an element in O(1);
delete(int element); //deletes an element in O(1);
lookup(); // returns any element in random from the list at O(1);
Write an algorithm that uses the divide and conquer technique. Given an array V with n int elements the algorithm should calculate the number of times that two consecutive 0's appear. Example :If V = [3, 0, 0, 1, 0, 1, 3, 2, 0, 0, 0, 1, 2], the algorithm should return 3, Note that 0, 0, 0 corresponds to having 2 pairs of consecutive zeros.
I was wondering if you guys can give me a step by step approach in solving these questions. I'm a recent grad and I want to know the best solutions to solve these problems. Thanks!
Sort the elements inside a stack using only push and pop opperation. Is it possible to do it only with one additional stack?
Build a function that takes one string and one regex expression in inputs and output true if the string matches the regex expression.
string: a-z
regex: a-z + * (where '*' matches 0 or more character and '+' matches one character)
O/p the expected value of the number of people to deliver the information
I/P dependency graph
1234
1-0111
2-1000
3-1001
4-1010
o/p
2.66
given a range of number 1 through N, where N >=3. you have to take an array of length 2N and place each number ( from the range 1 to N) twice. such a that the distance between two indexes of a number is equal to the number. example
N=3
( 3, 1, 2, 1, 3, 2 )
I know we can Use Backtracking but is there any other solution.
t's laundry day, and, as usual, you've been putting this off for quite some time. Also, unfortunately, you lacked the foresight to actually ensure all your dirty laundry stayed in your hamper whilst it accumulated (what? we can't ALL be underwear basketball pros!).
Begrudgingly, you've gathered up all the clothing you could find and sent them through the wash. Now you have a disheveled pile of clean, albiet disorganized, accoutrements. You come to the realization that you probably lost some items in the fray, so now it's time to fold and figure out what's gone missing!
To get a good idea of the state of your wardrobe, count up the number of distinct shirts, pants, and underwear you have as you go through the laundry. Also pair up your socks, noting the number of pairs of each kind of sock and if there are any lonely souls (single (and ready to mingle) socks).
Input Specifications
Each article of clothing will have its own separate line. You have a penchant for hoarding, so there is no guarantee as to the number of pieces, but you can assure yourself that each article can be easily categorized by description (name).
Articles of clothing will be fed in as line-delimited list. See below for examples.
Output Specifications
Output should be an alphabetically (case-insensitive) sorted, line-delimited list of the articles of clothing along with their count. Each field (count, category) should be separated by a pipe (|). If you come across a sock without a soulmate, the count should be designated by a 0 (zero). Socks that are in pairs should be on separate lines from the socks of the same category without pairs, and should come before the pairless sock. See below for examples.
Sample Input/Output
INPUT
white shirt
polka dot sock
red sock
superhero shirt
torn jeans
polka dot sock
white shirt
polka dot sock
OUTPUT
1|polka dot sock
0|polka dot sock
0|red sock
1|superhero shirt
1|torn jeans
2|white shirt
EXPLANATION
As described above in the input and output specifications.
In gmail, while composing an email, upon adding a contact, related contacts are displayed. How would you implement that feature?
- Write an algorithm for that.
- What data structure would you use to store the weights?
- In what format would you persist this data?
We have words and there positions in a paragraph in sorted order. Write an algorithm to find the least distance for a given 3 words.
eg. for 3 words
job: 5, 9 , 17
in: 4, 13, 18
google: 8, 19, 21
...
...
Answer: 17, 18, 19
Can you extend it to "n" words?
Context: In Google search results, the search terms are highlighted in the short paragraph that shows up. We need to find the shortest sentence that has all the words if we have word positions as mentioned above.
Write an algorithm to convert the given input string to the expected output string. The input string shall be the length of few million characters. So the output has to be updated in the same string...
Input String = "ABBCDEFGGGGGGGGHHXX..<20 more X>..XYY..."
Expected output = "A1B2C1D1E1F1G8H2X23Y2..."
Note: The count of each character has to be appended with the same character in the output string
There are N parking slots and N-1 cars. Everytime you can move one car. How to move these cars into one given order.
BTW: I got this question from internet but i could not figure it out partially because the description is kind of incomplete to me. Anyone knowing this question or the solution?
write an algorithm to decide weather a string is a palindrome.
Ignore any non-letter characters in the the string.
Ignore capital/lower case.
Space complexity O(1)
for example, the following should return true:
A man, a plan, a canal -- Panama!
Given a BST and a number x, check whether exists two nodes in the BST whose sum equals to x. You can not use one extra array to serialize the BST and do a 2sum solver on it.
Given a map, each road has a value denoting how many hours it takes to travel from adjacent cities. Each city has its own holiday. If you arrive at the city during its holiday, you can get one gift. However, in each week, you can only travel one time. Now you are initially placed in one city at the beginning of this year, how do you plan your traveling to get the maximal gifts.
There are many tourist sites and each has their own holiday. If you arrive there during the holiday, you can gain one gift. It costs you many hours Wij traveling from site_i to site_j. What's more, you can only travel once in one week. Now you are initially placed in one site, how do you plan your routine in this year to gain most gifts.
Given a BST and a number x, find two nodes in the BST whose sum is equal to x. You can not use extra memory like converting BST into one array and then solve this like 2sum.
Given an sorted array having duplicates and another which is not sorted and have duplicates.Find array b is found continuously in array a. if so print position of array b in array a
If i have a graph which have n vertices and n-k edges than How many connected component it has ?
Given an arraylist of N integers,
(1) find a non-empty subset whose sum is a multiple of N.
(2) find a non-empty subset whose sum is a multiple of 2N.
Compare the solutions of the two questions.
class template vs template class?
c++ specific properties?
struct vs class?
encapsulation vs abstraction?
Design a holder - bulbs(LED,Normal,Tube light) - uml relation ship?
multiple inheritance, multiple level inheritance-CTOR and DTOR order for base classes ?
why use templates?
what is abstract class?
unit testing tools used?
smart poiner vs dangling pointer
why we take "Base& obj" as input in Base Copy CTOR function, in Base(Base& obj){}, why not "Base obj".
shallow copy vs Deep copy.
Given a M * N matrix, if the element in thematrix is larger than other 8 elements who stay around it, then named thatelement be mountain point. Print all the mountain points.
In basket ball game for a player to win a game
challenge 1) 2 out of 3 throws should be basket
challenge 2) 4 out of 6 throws should be basket
which challenge should the player choose so that he might have better chance of winning the game?
In basket ball game for a player to win a game
challenge 1) 2 out of 3 throws should be basket
challenge 2) 5 out of 8 throws should be basket
which challenge should the player choose so that he might have better chance of winning the game?
How would test this method ?
public static bool DateBetweenDates(DateTime startDate, DateTime endDate, DateTime dateToTest)
{
if (startDate.Year > dateToTest.Year)
return false;
if (endDate.Year < dateToTest.Year)
return false;
if (startDate.Month > dateToTest.Month)
return false;
if (endDate.Month < dateToTest.Month)
return false;
if (startDate.Day > dateToTest.Day)
return false;
if (endDate.Day < dateToTest.Day)
return false;
else
return true;
}
Given graph below, and the Y-axis co-ordinates in and array, find the lowest point of every dip in the graph.
(I know graph looks horrible but i tried my best)
70 /
60 /\/
50 /
40 /\ /
30 / \ /
20 /\/ \/
10 /Array is : 0 10 20 10 30 40 50 40 30 20 10 20 30 40 50 60 50 60 70
Result List : 0 10 10 50
Given a +ve integer, find the next highest number in the numerical order using the same numbers present in the given integer.
Example : 218765
O/P : 251678
You are given the toplogical information of a terrain in the following format - There are n points ( x_i , y_i ) and for each point (x_i , y_i ) the altitude h_i is given.
For any rectangle (axis parallel) defined by the x-y coordinates of
the corner points, we must answer the query about which is the highest altitude point lying within the rectangle.
Implement this using a range-query data-structure that answers such a
query in O( log^2 n) time
Suppose we have array of N numbers. We will define N functions on this array. Each function will return the sum of all numbers in the array from Li to Ri ( Li is left index, Ri is right index). Now we have 2 types of queries:
Type1: 1 x y Change the xth element of the array to y
Type2: 2 l r Return the sum of all functions from m to n.
Input type:
First Line is the size of the array i.e. N
Next Line contains N space separated numbers Ai denoting the array
Next N line follows denoting Li and Ri for each functions.
Next Line contains an integer Q , number of queries to follow.
Next Q line follows , each line containing a query of Type 1 or Type 2
Here is an example:
Input:
5
1 2 3 4 5
1 2
3 4
1 4
1 5
3 5
5
1 1 5
2 2 4
2 1 3
1 4 5
2 1 5
Output:
40
28
63
Explanation:
Function 1 is sum of values from index 1 to index 2 = 1+2=3
So , F1=3
Similarly, F2=3+4=7
F3=1+2+3+4=10
F4=15
F5=12
Now when I query 1 1 5
means it is type 1 query, so we replace value at index 1 by 5.
So our new array is,
5 2 3 4 5
and
F1=7
F2=7(unchanged)
F3=14
F4=19
F5=12(unchanged)
Then next query is 2 2 4
means give sum of all functions from index 2 to 4.
So, ans= 7+14+19 =40 (output 1)
Similarly are other 2 outputs.
Index are 1 based in example.
Comment me if you are not clear with question.
Edit: I know one can do it with naive approach or using segment tree. But they wanted more faster way to do it.
Given a list of points, merge the intersecting points.
Example:
{-10,-5}{-1,5}{2,4}{5,10}{20,35}{12,17}{17,21}
Should output:
{-10,-5}{-1,10}{12,35}
Nothing falls between the {-10,-5} so this point stays. The {-1,5}{2,4} and {5,10} points can all be merged as they have intersecting points. They are merged to {-1,10}. The {20,35}{12,17} and {17,21} points can all be merged as they have intersecting points. They are merged to {12,35}
Write an function to judge whether the input String is a number?
For example: "-3.3425","80.0", both of them are number
Goldman's conjecture - already posted,
Well ordered numbers - already posted.
The cows and bulls game, Player A chooses a word and player B guesses a word. You say bulls when a character in the player B's guess match with a character in player A's word and also it is in the corect position as in A's word. You say cows, when a character in the player B's word match the character in player A, but it is not in the correct position. The characters are case insensitive. Given two words player A's and player B's,Write a function that return the number of bulls and no of cows. For example,
A - Picture B- Epic, bulls -0, cows - 4
A - forum B - four, bulls - 3 cows - 1
Jumper Game: A NxN grid which contains either of 0-empty, 1 - player1, 2 - player 2. Given a position in the grid, find the longest jump path. For jump path, you can horizontally or vertically, you can jump on opponent cell and also the landing cell should be empty. No opponent cell can be jumped more than once. Write a function which takes grid and a specific position in the grid, and returns the longest possible number of jumps in the grid.
Write code to get maximum and second maximum element of a stack. The given function should be in O(1) complexity . Later extend for finding kth max in O(1).
you are given an array or length 1million and rang of value from 0-m ... count the number of accurance of each number.
#2 the same array as above. find out the distance between min and max.
#3 write a malloc function.
and some theoretical Qs on routing Table.
There was one stupid guys who asked me given a binary tree and a depth of the tree print all the nodes in that tree on that depth.
when i used inserted a NULL node in my code he said it wont work as the value of NULL is 0 its not a pointer.... bla boa.... i was shocked that a guy who has code to take 3rd round of interview is saying these kind of thing :D..... there was one more thing that he said that in 'C' u cant declare a variable after the initial declaration in func tion body I said yes we should not but Now a days c compilers like gcc etc allows it ... god know he ever used gcc or not but he denied it 3 time..... really bad experience
Find compound words
input-> String (example "he has to go in a wheelchair")
output -> wheelchair = wheel chair
assume that you have a big dictionary to look up the words.
Please help with this question asked in interview?. I want to also understand why a particular data structure was chosen and what is the time complexity.
Given a stream of characters (stream is increasing char by char), check if newly
formed 10character word is present in already parsed/scanned stream. Print such
repeating streams lexicographically at the end.
Abstract
We are planning an orienteering game.
The aim of this game is to arrive at the goal (G) from the start (S) with the shortest distance.
However, the players have to pass all the checkpoints (@) on the map.
An orienteering map is to be given in the following format.
########
#@....G#
##.##@##
#..@..S#
#@.....#
########
In this problem, an orienteering map is to be given.
Calculate the minimum distance from the start to the goal with passing all the checkpoints.
Specification
* A map consists of 5 characters as following.
You can assume that the map does not contain any invalid characters and
the map has exactly one start symbol 'S' and exactly one goal symbol 'G'.
* 'S' means the orienteering start.
* 'G' means the orienteering goal.
* '@' means an orienteering checkpoint.
* '.' means an opened-block that players can pass.
* '#' means a closed-block that players cannot pass.
* It is allowed to move only by one step vertically or horizontally (up, down, left, or right) to the
next block.
Other types of movements, such as moving diagonally (left up, right up, left down and right down)
and skipping one or more blocks, are NOT permitted.
* You MUST NOT get out of the map.
* Distance is to be defined as the number of movements to the different blocks.
* You CAN pass opened-blocks, checkpoints, the start, and the goal more than once if necessary.
* You can assume that parameters satisfy following conditions.
* 1 <= width <= 100
* 1 <= height <= 100
* The maximum number of checkpoints is 18.
* Return -1 if given arguments do not satisfy specifications, or players cannot arrive at the goal
from the start by passing all the checkpoints.
1/6
Examination 1
*You can choose Java or C++
Given a set of road segments:
class Seg { int ID; int NextID; }
Implement a method that finds the longest connected stretch for a random collection of segments:
Seg[] FindLongest(Seg[] segs);
Assume that each NextID have a corresponding object with ID == NextID in the input. (-1 or any negative ID) indicates no link. No other assumptions about input should be made
Create corpus reader and tokenizer
Write a program that creates an inverted index for this corpus, allowing searching for free
text, e.g. [dor cabeça], [efeitos adversos]
a) Use the index structure and contents that you consider more suitable/relevant;
b) Use a default list of stopwords and accept as optional argument a text file with
stopwords; Add the option to disable the use of the stopword filter;
c) Use the Porter stemmer as default, but you should allow disabling this;
d) Add the option to write / read the index to / from a text file.
2. Implement a ranked retrieval method based on the vector-space model and using the tf-idf
weighting scheme.
2.1. Use the queries and the list of relevant documents to evaluate your implementation (note:
these will be available later). Calculate and report the average precision for each query and
the mean average precision (MAP) over all queries.
docs-> EMEA Corpus ->https://drive.google.com/folderview?id=0B3Slz0zk1PRUSkxuTlE2VVl1Ym8&usp=sharing
Write a program to read file of following data structure: Name: favcolor=blue Find out which color is favorite by most people (print the color and number of people)
You have a binary tree where each node knows the number of nodes in its sub-tree (including itself).
Given a node n and an int k,
write a function to return the kth
node in an in order traversal.
Can you do this non recursively
if an application hung in customer box , how to whether that is due to dead lock?
i suggested to take .dmp file and use windbg etc , but he said , he dont have that much time to take dump file etc. I suggested process explorer tool and if application hang , the top call in more than one thread will be like wait call. but he said he is looking for some other tool.
so any thoughts??
Find Maximum sum subarray such that no elemnt in subarray is repeated
https://www.facebook.com/photo.php?fbid=10152820917104183&set=pcb.1523587287892659&type=1&theater
/* Write a function to compute the maximum length palindromic sub-sequence of an array.
A palindrome is a sequence which is equal to its reverse.
A sub-sequence of an array is a sequence which can be constructed by removing elements of the array.
Ex: Given [4,1,2,3,4,5,6,5,4,3,4,4,4,4,4,4,4] should return 10 (all 4's) */
class Interview {
public static int maxLengthPalindrome(int[] values) {
//ur implementation here
}
/**
* Given a nested list of integers, returns the sum of all integers in the list weighted by their depth
* For example, given the list {{1,1},2,{1,1}} the function should return 10 (four 1's at depth 2, one 2 at depth 1)
* Given the list {1,{4,{6}}} the function should return 27 (one 1 at depth 1, one 4 at depth 2, and one 6 at depth 3)
*/
public int depthSum (List<NestedInteger> input)
{ // ur implementation here}
**
* This is the interface that represents nested lists.
* You should not implement it, or speculate about its implementation.
*/
public interface NestedInteger
{
/** @return true if this NestedInteger holds a single integer, rather than a nested list */
boolean isInteger();
/** @return the single integer that this NestedInteger holds, if it holds a single integer
* Return null if this NestedInteger holds a nested list */
Integer getInteger();
/** @return the nested list that this NestedInteger holds, if it holds a nested list
* Return null if this NestedInteger holds a single integer */
List<NestedInteger> getList();
}
Asked at Walmart Labs
----------------------------------
There is a row of seats. Assume that it contains 15 seats adjacent to each other. There is a group of people who are already seating in that row randomly. i.e. some are sitting together & some are scattered.
Take the row as a String in java.
The seat which is occupied is marked with a character 'X' & which is not occupied is marked with a dot '.'
Now your target is to make the whole group sit together i.e. next to each other and without having any vacant seat between them in such a way that the total number of hops or jumps at the end of the grouping them together should be minimum.
Ok let me try to explain you in details.
Here is the row having 15 seats represented by the String (0, 1, 2, 3, ......... , 14) -
. . . . x . . x x . . . x . .
Now to make them sit together one of approaches is - . . . . . . x x x x . . . . .
Following are the steps to achieve this -
1 - Move the person sitting at 4th index to 6th index - Number of jumps by him = (6 - 4) = 2
2 - Bring the person sitting at 12th index to 9th index - Number of jumps by him = (12 - 9) = 3
------------------------------------------------------------------------------------------------------------------------------------------------------------
So now the total number of jumps made = ( 2 + 3) = 5 which is the minimum possible jumps to make them seat together.
There are also other ways to make them sit together but the number of jumps will exceed 5 & that will not be minimum.
For example bring them all towards the starting of the row i.e. start placing them from index 0. In that case the total number of jumps will be ( 4 + 6 + 6 + 9 ) = 25 which is very costly and not an optimized way to do this movement.
Now write an algorithm which will return the minimum number of jumps required to make them sit together.
write code to validate if the input string has redundant braces?
((a+b)) - Has redundant braces.
(a+(b+c)) - This doesn't has redundant braces.
Find the unique number that is present only once in array while all the others are present three times.
Example: 2,3,5,1,2,2,5,3,5,3
Answer : 1 as 2,3,5 are repeated three times
Complexity should be better than O(nlogn)
Write a Java program to find out minimum numbers from fibonacci series required such that sum of numbers should be equal to a given Number N?
Note : repetition of number is allowed.
Example1.
N= 7;
answer = 2 (5 + 2 = 7)
Example 2.
N = 70;
Answer = 3 (34 + 34 + 2)
How many minimum numbers from fibonacci series are required such that sum of numbers should be equal to a given Number N?
Note : repetition of number is allowed.
Example1.
N= 7;
answer = 2 (5 + 2 = 7)
Example 2.
N = 70;
Answer = 3 (34 + 34 + 2)
Given the relative positions (S, W, N, E, SW, NW, SE, NE) of some pairs of points on a 2D plane, determine whether it is possible. No two points have the same coordinates.
e.g., if the input is "p1 SE p2, p2 SE p3, p3 SE p1", output "impossible".
Given an array of integer, find the number of un-ordered pairs in that array, say given {1, 3, 2}, the answer is 1 because {3, 2} is un-ordered, and for array {3, 2, 1}, the answer is 3 because {3, 2}, {3, 1}, {2, 1}.
Obviously, this can be solved by brute force with O(n^2) running time, or permute all possible pairs then eliminate those invalid pairs.
My question is does any body have any better solution and how would you do it because it seems like a dynamic programming problem. A snippet of code would be helpful
given expression with operands and operators (OR , AND , X-OR) , in how many ways can u evaluate the expression to true, by grouping in different ways? Operands are only true and false.
for example true & false | true ^ false can be grouped to true & ((false | true) ^ false) and so on..
the following wiki of the above question
http://en.wikipedia.org/wiki/Boolean_satisfiability_problem
Suppose we are given a set L of n line segments in the plane, where the endpoints of each
segment lie on the unit circle x^2 + y^2 = 1, and all 2n endpoints are distinct. Describe
and analyze an algorithm to compute the largest subset of L in which no pair of segments
intersects.
reverse nodes in k interval in single linked list
eg. k = 3
i/p 1 2 3 4 5 6 7 8 9
o/p 3 2 1 6 5 4 9 8 7
find if two people are connected in social network.
you wrote a c++ program and your processor change (eg. from intel to ARM or anything ) then what are thing needs to be change in compiler to get the same behavior of program in different (eg. ARM ) architecture machine.
There is a rectangle with left bottom as (0, 0) and right up as (x, y). There are n circles such that their centers are inside the rectangle. Radius of each circle is r. Now we need to find out if it is possible that we can move from (0, 0) to (x, y) without touching the circle. We can move freely anywhere.
How does map-reduce work? Explain with diagram.
Difference Between Call by Value and Call by Ref.
what is virtual function?
Give an example scenario of use.
In a matrix of characters, find an string. String can be in any way (all 8 neighbors to be considered), like find Microsoft in below matrix.
A-C-P-R-C
X-S-O-P-C
V-O-V-N-I
W-G-F-M-N
Q-A-T-I-T
String Microsoft is present in the matrix above ?
There also a slight variation where a diagonal neighbor is not considered.
Solve the above problem for N number of input arrays. Find the intersection of N-integer arrays.
Given two integer arrays, find the intersection of the two.
eg: arr1 = {1, 3,6,10}, arr2 = {2,3,5,6} , the function should return {3,6}.
Given two strings, return boolean True/False, if they are only one edit apart.Edit can be insert/delete/update of only one character in the string. Eg:
-True
xyz,xz
xyz, xyk
xy, xyz
-False
xyz, xyz
xyz,xzy
x, xyz
calculate the summary statistics for a fleet of hosts. Each host has a fixed number of slots in which virtual instances can run. Each host can only run instances of a particular type, e.g. M1, M2, or M3. You are provided with the file “FleetState.txt” that contains the state of the fleet. Each line in the file represents a single host in the following comma-separated format:
<HostID>,<InstanceType>,<N>,<Slot1State>,<Slot2State>,…,<SlotNState>
where
<HostID> is an integer
<InstanceType> can be M1, M2, or M3
<N> is the total number of slots on the machine
<SlotjState> is 0 if slot j is empty and 1 if it is occupied by an instance
Write a program that loads the state of the fleet from the input file “FleetState.txt” and then computes and writes out the following summary statistics to the output file “Statistics.txt”:
For each instance type, the count of empty hosts (all slots empty)
For each instance type, the count of full hosts (all slots filled)
For each instance type, the count of the most filled hosts (having the smallest number of empty slots > 0). Both the host count and number of empty slots must be written out in that order.
The output file must have the following format:
EMPTY: M1=<count>; M2=<count>; M3=<count>;
FULL: M1=<count>; M2=<count>; M3=<count>;
MOST FILLED: M1=<count>,<empty slots>; M2=<count>,<empty slots>; M3=<count>,<empty slots>;
What is the best way to solve this problem?
calculate the summary statistics for a fleet of hosts. Each host has a fixed number of slots in which virtual instances can run. Each host can only run instances of a particular type, e.g. M1, M2, or M3. You are provided with the file “FleetState.txt” that contains the state of the fleet. Each line in the file represents a single host in the following comma-separated format:
<HostID>,<InstanceType>,<N>,<Slot1State>,<Slot2State>,…,<SlotNState>
where
<HostID> is an integer
<InstanceType> can be M1, M2, or M3
<N> is the total number of slots on the machine
<SlotjState> is 0 if slot j is empty and 1 if it is occupied by an instance
Write a program that loads the state of the fleet from the input file “FleetState.txt” and then computes and writes out the following summary statistics to the output file “Statistics.txt”:
For each instance type, the count of empty hosts (all slots empty)
For each instance type, the count of full hosts (all slots filled)
For each instance type, the count of the most filled hosts (having the smallest number of empty slots > 0). Both the host count and number of empty slots must be written out in that order.
The output file must have the following format:
EMPTY: M1=<count>; M2=<count>; M3=<count>;
FULL: M1=<count>; M2=<count>; M3=<count>;
MOST FILLED: M1=<count>,<empty slots>; M2=<count>,<empty slots>; M3=<count>,<empty slots>;
what is the best way to solve it?
Got this sh***y problem.
A judge tells a person under trial that if your answer is true, you get 2 year sentence and if your answer is false you get 3 year sentence. The person under trial gives an answer which made the judge set him free. What did he say?
How to impliment a method to track devices using mac addresses in a wifi lan in java?
== Question ==
Given a list of TestResult, where each result contains a test score, a student ID and a date, figure out the students' final scores. A final score is the average of a student's top 5 scores.
Here is a sample of the list of TestResult:
50 JACK 5/14/2013
89 ALICE 3/25/2012
70 BOBBY 12/7/2010
60 JACK 8/9/2013
99 MIKE 9/11/2011
100 JOHN 7/4/2011
38 JACK 1/28/2014
46 JACK 11/15/2012
<... more ...>
struct TestResult {
score,
student_id,
date,
}
The third question is a brain teaser: if 1000 couples are to give birth to male and female babies(50% change each), and they would keep giving birth until they have a girl, what's the boy to girl ratio in 20 years
A parent array P is given where P[i] denotes the parent of the ith node in the tree(the tree is generic). Parent of root is indicated with -1. I need to find the height/depth of tree. (Best sol in O(n))
Given an array of object A, and an array of object B. All A's have
different sizes, and all B's have different sizes. Any object A is of the
same size as exactly one object B. We have a function f(A, B) to compare the
size of one A and one B. But we cannot compare between two A's or two B's.
Give an algorithm to match each A with each B.
2.
String encode(List<String> input);
List<String> decode(String input);
This is two questions I got from a google interview. Not very sure how to solve it. Any comments would be appreciated.
1.
interface RateLimit {
/** Sets the rate, from 1 to 1000000 queries per second */
void setQPS(int qps);
/** accept or reject a request, called when request is received */
boolean allowThisRequest();
}
brief example:
server instantiates your object, calls setQPS(1)
at at time t, user1 makes a request, allowThisRequest() returns true
at time t+0.01 sec, user2 makes a request, allowThisRequest() returns false
at at time t+1, user4 makes a request, allowThisRequest() returns true
at time t+5 sec, user3 makes a request, allowThisRequest() returns true
We have two strings A and B with the same super set of characters. We need to change these strings to obtain two equal strings. In each move we can perform one of the following operations:
1. swap two consecutive characters of a string
2. swap the first and the last characters of a string
A move can be performed on either string.
What is the minimum number of moves that we need in order to obtain two equal strings?
given n > 0 fair dice with m > 0 "sides", write an function that returns a histogram of the frequency of the result of dice rolls. For example, for two dice, each with three sides, the results are:
(1, 1) -> 2
(1, 2) -> 3
(1, 3) -> 4
(2, 1) -> 3
(2, 2) -> 4
(2, 3) -> 5
(3, 1) -> 4
(3, 2) -> 5
(3, 3) -> 6
And the function should return:
2: 1
3: 2
4: 3
5: 2
6: 1
Given n rows of integers, such that the ith row (1 <= i <= n) contains i integers, find the path having the maximum weight.
Path traversal rules:
1. A valid path sequence would be top-down i.e. begins with the integer in the first row, and traverses all rows selecting only one integer in each row.
2. From any jth integer in the ith row i.e row[i][j], traversal can happen either downward (i.e to row[i+1][j]) or diagonally downward to the right (i.e to row[i+1][j+1])
The weight of a Path is the sum of values of integers in the Path sequence.
Sample Input:
No. of Rows: 5
4
2 9
15 1 3
16 92 41 44
8 142 6 4 8
Expected Output: 4, 2, 15, 92, 142 (Max weight is 255)
Given two integer arrays. Find the Largest Common sub array. For example,
arr1 = {1,2,3,2,3,2} arr2={2,2,3,3,4,5}, the largest common sub array is {2,2,3,3}
int fun()
{
/*write code here.*/
}
int main()
{
int i=10;
fun();
printf("%d",i);
}change the value of the i without changing code of the main function, assign 20 to i ?
Question: Two players A and B are playing a game. Pots of gold, each with
varying number of coins are placed in a single line. The rules of the game are:
1) Players play turn by turn.
2) On each turn a player can pick a pot of gold from either end of the line. He
gets all the gold in that pot. The next pot of gold on that end is now available
for picking.
What is the maximum number of gold can the first player get ?
a left grow binary tree. Describe as below. (Transform from A to B)
A: B:
1 1
/ \ /
2 3 2 - 3
/ \ /
4 5 4 - 5
/ \ /
6 7 6 - 7
a left grow binary tree. Describe as below. (Transform from A to B)
A: B:
1 1
/ \ /
2 3 2 - 3
/ \ /
4 5 4 - 5
/ \ /
6 7 6 - 7
Given ~300k words with an average length of 7 in a file.
All words are dictionary correct words.
Print all the anagrams that are present in this list of words without repeating them.
E.g. if the list has:
ACT
BAT
CAT
TAB
TAC
print:
ACT, CAT, TAC
BAT, TAB
Design the algorithm and the system for a WebCrawler.
The webcralwler will be provided millions of URLs. The webpage will be downloaded and then parsed for more URLs. If more URLs are found then they should also be downloaded and parsed.
He was interested in:
1. Scale to handle millions of URLs
2. What are the bottle necks in the system? How will you resolve them
Design a vending machine
Given a sorted array with some sequenced numbers and some non-sequenced numbers. Write an algorithm that takes this array as an input and returns a list of {start, end} of all consecutive numbers. Consecutive numbers have difference of 1 only.
E.g. of array:
[4, 5, 6, 7, 8, 9, 12, 15, 16, 17, 18, 20, 22, 23, 24, 27]
public class Range
{
private int begin;
private int end;
public int begin { get; set; }
public int end { get; set; }
}1. Consider an ordinary binary min- heap data structure with n elements supporting the instructions INSERT and EXTRACT-MIN in O(lg n) worst case time. Give a potential function f such that the amortized cost of INSERT is O(lg n) and the amortized cost of EXTRACT-MIN is O(1) , and show that it works.
Implementing Deque using 3 Stacks (Amortized time O(1)) , I can't solve this problem ???
Amortized time O(1) what is Amortized time O(1)) ????
There are two coins that make 55 cents. If one of them is not nickle then what are the two coins?
A bear have to climb a 60.5 feet long hill. It climbs 3 feet in every minute before it fall down for 2 feet. How long it will take to climb the hill?
Create a random number generator within the given range? what if no range given? it should not repeat the sequence of random numbers generator before and after JVM is re-booted?
Create a random number generator within the given range or without range, it should repeat the sequence of random numbers generator before and after JVM is re-booted
Colorful Number:
A number can be broken into different sub-sequence parts. Suppose, a number 3245 can be broken into parts like 3 2 4 5 32 24 45 324 245. And this number is a colorful number, since product of every digit of a sub-sequence are different. That is, 3 2 4 5 (3*2)=6 (2*4)=8 (4*5)=20 (3*2*4)= 24 (2*4*5)= 40
But 326 is not a colorful number as it generates 3 2 6 (3*2)=6 (2*6)=12.
You have to write a function that tells if the given number is a colorful number or not.
A string "aBIY" is said to be a well-ordered word as each of the letters are in sequential manner regardless of case. So, "AbLe" is not a well-ordered word.
You are a anti-hacker. you have a number of character sequences. Your task is to generate all possible well-ordered word that can be generated by those numbers of given character sequences.
Edge Detection:
Two-dimensional array representation of an image can also be represented by a one-dimensional array of W*H size, where W represent row and H represent column size and each cell represent pixel value of that image. you are also given a threshold X. For edge detection, you have to compute difference of a pixel value with each of it's adjacent pixel and find maximum of all differences. And finally compare if that maximum difference is greater than threshold X. if so, then that pixel is a edge pixel and have to display it.
You're given a dictionary of strings, and a key. Check if the key is composed of an arbitrary number of concatenations of strings from the dictionary. For example:
dictionary: "world", "hello", "super", "hell"
key: "helloworld" --> return true
key: "superman" --> return false
key: "hellohello" --> return true
Given a set of equalities and inequalities like A=B,B=C,F=J and A!=C, etc in two separate arrays (equalities[] and inequalities[]) and a method, separate that returns the two objects, e.g. separate(A=B) will return A and B, write an algorithm to find whether the entire set is consistent in constant time.
By saying that an algorithm runs in O(n) time in the worst case, what does we really mean?
Use the shorest unique prefix to represent each word in the array
input: ["zebra", "dog", "duck",”dot”]
output: {zebra: z, dog: do, duck: du}
[zebra, dog, duck, dove]
{zebra:z, dog: dog, duck: du, dove: dov}
[bearcat, bear]
{bearcat: bearc, bear: ""}
Java: You're given a very large array of char's. Write a method to remove duplicates in the array, in place. Optimize for space complexity, not time complexity.
Say you're the development lead for a mobile application. A user submits a bug report saying that something isn't working right even though internal tests show that it should. What do you do?
Write a function that takes a array of strings and prints out the number of anagrams in the array
[count,dog,cat,act]
count:1
dog:1
cat:2
act:2
Having a home-defined linked list with the following structure, where the next will point to the next node in the list and the random will point to a random node in the list (not null).
Create a copy of the structure (the data field in each node is not unique for different nodes):
/*
Example:
Having the list:
1 -> 2 -> 3 -> X
With random pointers to:
1: 3
2: 2
3: 1
Create the list:
1' -> 2' -> 3' -> X
1': 3'
2': 2'
3': 1'
*/
class Node {
int data;
Node next;
Node random;
}
You are driving a bus along a highway, full of rowdy, hyper, thirsty students and a soda fountain
machine. Each minute that a student is on your bus, that student drinks one ounce of soda. Your
goal is to drop the students off quickly, so that the total amount of soda consumed by all students
is as small as possible.
You know how many students will get off of the bus at each exit. Your bus begins somewhere
along the highway (probably not at either end) and move s at a constant speed of 37.4 miles per
hour. You must drive the bus along the highway; however, you may drive forward to one exit then
backward to an exit in the opposite direction, switching as often as you like. (You can stop the
bus, drop off students, and turn around instantaneously.)
Describe an efficient algorithm to drop the students off so that they drink as little soda as
possible. Your input consists of the bus route (a list of the exits, together with the travel time
between successive exits), the number of students you will drop off at each exit, and the current
location of your bus (which you may assume is an exit).
I gave a recursive solution but he insisted on dynamic programming which i couldn't give
Given an array of paper products in which each product has an attribute name, width, and height, and given a sheet of paper that has width xx and height yy, write a program that returns the number of sheets of paper needed to print out the array of paper products
Print combinations of strings from List of List of String
Example input: [[quick, slow], [brown, red], [fox, dog]]
Output:
quick brown fox
quick brown dog
quick red fox
quick red dog
slow brown fox
slow brown dog
slow red fox
slow red dog
Write a function that takes a list of positive integers as an input, and returns all of the pairs of integers it contains that sum to 100. You can assume that all inputs are between 1 and 99.
what is the heartbleed attack in Network security
You are given with an array of 1s and 0s. And you are given with an integer m, which signifies number of flips allowed.
find the position of zeros which when flipped will produce maximum continuous series of 1s.
e.g.
input:
arr={1 1 0 1 1 0 0 1 1 1 } m=1
output={1 1 1 1 1 0 0 1 1 1} position=2
arr={1 1 0 1 1 0 0 1 1 1 } m=2
output={1 1 0 1 1 1 1 1 1 1} position=5,6
Given a string (1-d array) , find if there is any sub-sequence that repeats itself.
Here, sub-sequence can be a non-contiguous pattern, with the same relative order.
Eg:
1. abab <------yes, ab is repeated
2. abba <---- No, a and b follow different order
3. acbdaghfb <-------- yes there is a followed by b at two places
4. abcdacb <----- yes a followed by b twice
The above should be applicable to ANY TWO (or every two) characters in the string and optimum over time.
In the sense, it should be checked for every pair of characters in the string.
This test was on https://www.hackerrank.com
Input is a string of Bytes E.g.341B
Convert it to human readable form: 3 characters long (excluding decimal)
No trailing or leading zeros
E.g:
Input 341B
Output 341B
Input 12345B
Output 12.3K
Input 1234567B
Output 1.23M
Input 1000000000B
Output 1G
Do not round off
Assume input will not be more than 1G
For this problem 1000B = 1K, so on and so forth
Write 4 testcases for the usecase "Customer buys a book with the credit card payment option."
Write 4 testcases for the usecase "Customer buys a book with the credit card payment option."
Write 4 testcases for the usecase "Customers buy a book with the credit card payment option."
Write a test plan for the first time launch of a website that will sell digital books.
We are given a specific time(like 02:23), we need to get the angle between hour and minute(less than 180)
Given an array of numbers print the values in diagonal format.
Example (1) for 8 dataset
Input Array : [1, 2, 3,4,5,6,7,8]
Output
01 02 04 07
03 05 08
06
Example (2) for 45 dataset
Input Array: [1, 2, 3,4,5,6,7,8,9,10……….44, 45]
Output
01 02 04 07 11 15 19 23 27 31 35 39
03 05 08 12 16 20 24 28 32 36 40 43
06 09 13 17 21 25 29 33 37 41 44
10 14 18 22 26 30 34 38 42 45
Code in Java.
Write a program to implement Double Linked List from Stack with min. complexity.
Given a string and a regular expression pattern, give the number of times the pattern occurs in the string. RegEx example means as follows:
. – 2 occurrences of the previous character
+ – 4 occurrences of the previous character
* – more than 5 occurrences of the previous character
Sample Input:
5
aaaaaannndnnnnnnfffhfhhgjjjwkkkllclc
a.
n+
a*
an.
a.d.
Sample Output:
5
3
2
1
0
Write a method to create a deep-clone of an instance of the class Drawing.
public class Drawing {
public List < Shape > shapes = new LinkList < Shape >();
}
where shape is an abstract class which can have many concrete implementation
public abstract class Shape implements Serailizable {
---
}
Write a method to create a deep-clone of an instance of the class Drawing.
public class Drawing {
public List<Shape> shapes = new LinkedList<Shape>();
}
where shape is an abstract class that can have many concrete implementations:
public abstract class Shape implements Serializable {
}
Write test cases for adobe reader , Adobe flash player ,
What functionality and technicality you want to add in new media player when you are going to launch it in current market.
What functionality and technicality you want to add in new Operating system when you are going to launch it in current market.
What functionality and technicality you want to add in new web browser, when you are going to launch it in current market.
What functionality and technicality you want to add in mobile phone when you are going to launch it in current market.
Given number of digits of a phone number and number of disallowed digits as input, find all permutations of numbers which do not have two adjacent numbers the same, i.e. 1232 is allowed but not 1223. Disallowed digits can be upto 3, and can be included along with the phone number. Also the phone number should start with 4 if it contains the number 4.
The decimal and octal values of some numbers are both palindromes sometimes. Find such numbers within a given range.
If one and a half teenagers, eat one and a half pizzas in one and a half days, how many pizzas can 9 teenagers eat in 3 days
How to implement split () method
How to implement split () method
Write a program to split a string without using split()method
Replace %20 with ' '.
E.g. input: www.space%20.com
output: www.space .com
Suppose I am given a set of input strings input[5](five of them) and their corresponding replacement strings replace[5]. Then I am given an input text, how can I replace the strings in the text matching any of the inputs with their corresponding replacements.
Also I have to make sure that if suppose, I find a match input[0] and I replace it by replace[0], then because of that it could be possible that I have a new match for input[2] lets say because of the new characters added by replace[0]. I don't want to make replacements with replace[2].
Also I cannot use regex of java.
Suppose I am given a set of input strings input[5](five of them) and their corresponding replacement strings replace[5]. Then I am given an input text, how can I replace the strings in the text matching any of the inputs with their corresponding replacements.
Also I have to make sure that if suppose, I find a match input[0] and I replace it by replace[0], then because of that it could be possible that I have a new match for input[2] lets say because of the new characters added by replace[0]. I don't want to make replacements with replace[2].
Suppose I have five strings input[5] and their corresponding replacements replace[5]. I am given an input text and I want to find the occurence of any of the input strings and replace them with the corresponding replace strings. I cannot use regex. How can I do it. Also I have to make sure that lets say after replace input[0] with replace[0], if a new string arises due to replace[0] that matches with lest say input[2], then I cannot replace it with replace[2].
Find the 90th percentile of a stream of numbers between 1 and 10^6.
Followup: What if there is not enough memory to store all numbers and no upper bound.
Given an array of n positive numbers.
You need to find the maximum sum of contiguous sub array with special case. If in sub array 2 or more numbers are same except them from sum.
For example:
In:1 2 3 1 4 3 4 1 2
Out:10 (2,3,1,4)
In:11 5 7 4 11 7 4 2 2 5 9 4 5 11 5 1
Out:36 (11,7,4,2,2,5,9)
Goldbach's conjecture : Every even integer greater than 2 can be expressed as the sum of two primes.
Write a function which takes a number as input, verify if is an even number greater than 2 and also print atleast one pair of prime numbers.
Design & Implement your own Json parser. It should handle all cases. And it should also JUnit testable.
There is a particular sequence that only uses numbers 1, 2, 3, 4 and no two adjacent numbers are the same.
Write a program that given n1 1s, n2 2s, n3 3s, n4 4s will output the number of such sequences using all these numbers.
Output your answer modulo 1000000007 (10^9 + 7).
How do we represent any shape? And how do we say that two shapes are the same?
Input : {7,4,2,5,1,9,6}
Output :{1,4,6 ,9,7, 5, 2}
design a algo so that it receive an input
787668
787787
787948
787980
788094
788124and produce the output the difference of two consecutive numbers
119,161,32,114,30the input can varry to any length
desing a algo so that it receive an input
787668
787787
787948
787980
788094
788124and produce the output the difference of two consecutive numbers
119,161,32,114,30the input can varry to any length
Solve T(n) = 2T(n-2) + 1.
Solve T(n) = 2T(n/2) + 2n log n.
Solve T(n) = 2T(n/2) + n.
Given an input string, write a function that returns the Run Length Encoded string for the input string.
For example, if the input string is “wwwwaaadexxxxxx”, then the function should return “w4a3dex6″.
Given a string .Check if the string is palindrome or not
Lets assume I have a paper in the size of 8" by 11". How would I go about designing an algorithm that optimally fit smaller cards onto the paper.
Now I don't have the actual card dimensions but for this example lets assume the smaller cards are 3" by 4", 7" by 2" and 5" by 3".
Suppose S and T are two ordered dictionaries each containing n items. Both are implemented via sorted arrays and do not have any keys in common. Describe
an O(log n)-time algorithm that outputs the item whose key is the lower median in the union of S and T. For example, when the keys stored in S and T are
S = [3, 6, 7, 9] and T = [−1, 1, 2, 8], the lower median key is 3.
The stepping number:
A number is called as a stepping number if the adjacent digits are having a difference of 1. For eg. 8,343,545 are stepping numbers. While 890, 098 are not. The difference between a ‘9’ and ‘0’ should not be considered as 1.
Given start number(s) and an end number(e) your function should list out all the stepping numbers in the range including both the numbers s & e.
I was having an interview and here is the question:
If there are different pairs of characters, each pair of the characters means the two matching characters are the same. Print out all the identical characters.
For example:
if you have pairs:
A-B
C-D
E-F
G-H
A-D
F-G
you should print out:
{A, B, C, D} are the same characters.
{E, F, G, H} are the same characters.
Does anyone know how to solve this problem by not using brutal force?
Given a NXN matrix, starting from the upper left corner of the matrix start printing values in a counter-clockwise fashion.
Eg: Consider N = 4
Matrix= {a, b, c, d,
e, f, g, h,
i, j, k, l,
m, n, o, p}
Your function should output: dcbaeimnoplhgfjk
Another example would be
C I P E
R N K U
U O W O
L E S Y
The function should print: EPICRULESYOUKNOW
Problem statement:
we have a string of length N. can you figure out the number of occurrence of the most frequent substring in this string? we are only interested in substring of length from K to L and in each substring the number of distinct characters must not exceed M. the string contain only lower-case letters(a-z).
constraints:
2<=N<=100000
2<=k<=L<=26,L<N
2<=M<=26
sample input
5
2 4 26 // value of K L M
abcde
sample o/p
1
Given a String s and a hashmap containing certain decodings for all the characters of alphabet. Find all possible passwords that can be generated by replacing decodings in the string s.
Note that decodings of a charachter can only be single charachters
Eg: String s="abcde"
decodings given
a-{1,2,p,o,q}
b-{2,y}
c-{p}
d-{4,a,m,n}
e-{9,z,x}
h-{1}
'
'
'
x-{0}
y-{4,k,l}
z-{r,5}
So possible set passwords will be
abcde,1bcde,2bcde,pbcde,obcde,qbcde, //replace a with all possible decodings
a2cde,12cde,22cde,p2cde,o2cde,q2cde,aycde,1ycde,2ycde,pycde,oycde,qycde //replace b will all possible decodings
a2pde,12pde,22pde,p2pde,o2pde,q2pde,aypde,1ypde,2ypde,pypde,oypde,qypde.....//replace c will all possible decodingsImplement bool isPalindrome(SingleLinkList *node) in constant Space.
Sorry for incomplete post earlier..
Implement bool regex() Function.
Implement bool isBST(Tree * root)
Given a file which contains large number of strings.
e.g.:my name is XYZ. My emansi XYZ i.e. it has words and reverse of words. There can be the case where no reverse word is present.He told me to print all those pair whose reverse is also present in the file.
For above example output will be:
{name,eman}, {is, si}
Constraints were Minimum space should be used and time complexity should be minimum, further he added don’t compute reverse of string at all.
Write code to sum 2 integer but u cant use a+b method, you have to use either ++ or --. How you will handle negative numbers.
Hi,
Anyone here who has given the Amazon work style and personality test for the SDE/SDET position? If someone could shed some light on what exactly it is?
Hi,
Anyone here who has given the Amazon work style and personality test for the SDE/SDET position? If someone could shed some light on what it is exactly?
Given an array arr=[5,2,-3,4,1]
print
_ _ * * * * *
_ _ * *
* * *
_ _ * * * *
_ _ *
Note [In real question, replace _ by blank(or space)]. So, while solving this question need to replace _ by blank ].
Find all the calendar events which are overlapping.
Suppose there is event A: 10-15 Oct, B : 12-14 Oct , C:15-24 Oct, D: 23-34 Oct, E: 4-5 Oct
All events except E should be marked as overlapping as they overlap with some other event.
Find all the calender events which are overlapping.
Suppose there is event A: 10-15 Oct, B : 12-14 Oct , C:15-24 Oct, D: 23-34 Oct, E: 4-5 Oct
All events except E should be marked as overlapping as they overlap with some other event.
You're given an array of integers(eg [3,4,7,1,2,9,8]) Find the index of values that satisfy A+B = C + D, where A,B,C & D are integers values in the array.
Eg: Given [3,4,7,1,2,9,8] array
The following
3+7 = 1+ 9 satisfies A+B=C+D
so print (0,2,3,5)
You are given a string S. Each character of S is either ‘a’, or ‘b’. You wish to reverse exactly one sub-string of S such that the new string is lexicographically smaller than all the other strings that you can get by reversing exactly one sub-string.
For example, given ‘abab’, you may choose to reverse the substring ‘ab’ that starts from index 2 (0-based). This gives you the string ‘abba’. But, if you choose the reverse the substring ‘ba’ starting from index 1, you will get ‘aabb’. There is no way of getting a smaller string, hence reversing the substring in the range [1, 2] is optimal.
Input:
First line contains a number T, the number of test cases.
Each test case contains a single string S. The characters of the string will be from the set { a, b }.
Output:
For each test case, print two numbers separated by comma; for example “x,y” (without the quotes and without any additional whitespace). “x,y” describe the starting index (0-based) and ending index respectively of the substring that must be reversed in order to acheive the smallest lexicographical string. If there are multiple possible answers, print the one with the smallest ‘x’. If there are still multiple answers possible, print the one with the smallest ‘y’.
Constraints:
1 ? T ? 100
1 ? length of S ? 1000
Sample Input:
5
abab
abba
bbaa
aaaa
babaabba
Sample Output:
1,2
1,3
0,3
0,0
0,4
If a matrix of type float is casted to char *, how is it represented in memory, how to access the array elements.
float mtrx[200][200] ={ {0}};
char *ptr = (char*)(& mtrx[i][j]);A Multi-threaded server application stops working and the last log message from the application is:
"Some Server Related Message..."Code looks like:
CalledFunc ()
{
Code ...
Acquiring Thread lock
Line printing "Some Server Related Message..."
Func();
Releasing Thread Lock
}1. What should the programmer in charge do to debug this?
2. What has happened wrong in the Func()?
3. If an exception is thrown in the Func() what should be done to fix problem ?
A Multi-threaded server application stops working and the last log message from the application is:
"Some Server Related Message..."Code looks like:
CalledFunc ()
{
Code ...
Acquiring Thread lock
Line printing "Some Server Related Message..."
Func();
Releasing Thread Lock
}1. What should the programmer in charge do to debug this?
2. What has happened wrong in the Func() ?
3. If an exception is thrown in the Func() what should be done to fix problem ?
compare the time complexity of quick ,merge and bubble sort
Form Tree from following data
I have data like this
6 has parent SET 5,4
5 has parent SET 3,4,1,2
4 has parent SET 2,1,4
3 has parent SET 2,1
I need to create tree like
1 --> 2 --> 3 --> 4 --> 5 --> 6
OR
2--> 1--> 3--> 4-- >5 --> 6
Because there is no enough info about 1-->2 or 2--> 1
find out the subset of an array of continuous positive numbers from a larger array whose sum of of the elements is larger in comparision to other subset. eg: {1,2 5 -7, 2 5} .The two subarrays are {1,2,5} {2,5} and the ans is {1,2, 5} as its sum is larger than{2,5}
public abstract class Session{
private Object objectId;
//... other fields
public abstract void processRequest(InputStream in);
}
public XmlSession implements Session{
public void processRequest(InputStream in){
System.out.println("XML RESPONSE");
// DO STUFF TO XML RESPONSE
}
}
public JSonSession implements Session{
public void processRequest(InputStream in){
System.out.println("JSON RESPONSE");
// DO STUFF TO JSON RESPONSE
}
}
public static void main(String args[]){
Session session = new XmlSession();
session.processRequest();
Session session = ....;
session.processRequest();
}I would like to change my design in a way that I will not lose the Session object and I don't change the client code that instanciate the XmlSession.
Could it be useful the prototype pattern? If yes why?
There is a two storey home. We have three switch on the first floor and three rooms on the second floor. You can go upstairs only once and can touch switches only one. How will you find out which switch is for what room?
Given two classes C1 and C2 which are almost same.(remember not exactly same).
You want to choose best among these classes so that it can be use as key in hashmap.
What question will you ask regarding two classes C1 and C2.
Given a binary tree and a range as min and max.
Modify the tree such that number formed by traversing tree from root to leaf all fall in given range.
1
2 3
4 5 6 7
let say range is 125 - 136
Modified tree
1
2 3
null 5 6 null
Given a sorted array. Now following operations may be applied on even position elements:
swap elements on even position. An element may be swap only once.
eg. 1 2 3 4 5 6 7 8 9 10
modified array:
1 2 3 8 5 10 7 4 9 6.
Find any given element in less than o(n) complexity.
Given a sorted array, construct Balanced BST
Find all the Leaders in an Array.
An Array element is Leader if all the elements following that array element is lesser than or equal to it.
Ex: Arr = {13, 17, 5, 4, 6, 2}
O/p: 17, 6, 2
Given a number M (N-digit integer) and K-swap operations(a swap
operation can swap 2 digits), devise an algorithm to get the maximum possible integer?
Examples:
M = 132 K = 1 output = 312
M = 132 K = 2 output = 321
M = 7899 k = 2 output = 9987
M = 8799 and K = 2 output = 9987
Two dices are tossed. Once die is regular and the other is biased with probabilities P(1) = P(6) = 1/6, P(2) = P(4) = 0, P(3)= P(5) = 1/3.
Determine the probabilities of obtaining the sum 4.
write a program to find the minimum value in an unsorted array of integers. how many assignment operations happen within the loop?
what does this code do?
unsigned mystery(unsigned x) {
unsigned i=0;
while(x) {
x=x&(x-1);
i++;
}
return i;
}write a program to return min value from an unsorted array of integers. How many assignment operations happen within the loop?
what does this code do?
unsigned mystery(unsigned x) {
unsigned i=0;
while(x) {
x=x&(x-1);
i++;
}
return i;
}You are writing a simulation for a print server. This print
server can accept jobs from 3 places - network, USB, or operator. It can dispatch only one job at a time. Each input job should contain an integer t which is the time in seconds it will take to process the job. Write a multi-threaded program to simulate the server and provide some simulated load with jobs. Think, of some interesting statistics your program should emit and code them in.
We have 'n' patients and 'm' problems. The problems are of boolean type. Eg diabetes problem would be 'T' if a patient has it or 'F' otherwise. Suggest the data structure you would store this scenario on?
Q: We have a set of problems {diabetes, liver disease, kidney disease} find all the patients who have at least the 3 problems from the set.
The number of patients can be huge (n).
The number of problems not comparatively huge (m).
Which would be the best data structure to store these kind of records, so that we have a better search time.
Write a function to find the nth "ugly number". ugly numbers are numbers that can only be fully divided by 1, 2, 3, 5 and itself.
The Question is to find 4 numbers between 1 and 40, so that you can get all the numbers between 1 to 40 by doing either of operation below.
1) Either any of the four number itself.
2) creating an expression by combining among the four number, with either addition or subtraction.
For example suppose we have to find four numbers so that we can get numbers between 1-30.
The answer to above question is 1,3,6,20.
Write a function which gives the length of the largest palindrome found within a string.
Write a function that detects if a string is a palindrome.
1st Face to face
--------------------
Find if any string has repetitions or not.
Ababababab - true
Abcabcabcx - false
Abcdabce - false
Abaaabaaabaa - true
Virtual functions?
2nd facte to face
----------------------
Create a strategy for testing flipkart.com (any e-com site)
Suppose it is under development.
- I started with UI testing but he said that UI is developed in end
- What all positive scenarios to be tested? Negative scenarios to be tested?
- How you will ensure integration
What all type of testing should be done?
Explain observer design pattern.
Write a code in which the client registers some method on Registrar and the registrar calls that method in case some event happens.
- I created a hash table for events and function pointers but he was more worried about my testing knowledge.
You have an array of 0's and 1's. Determine a window [L,R], such that if you flip the bits in that window, you will have maximum number of 1's in your array, and then output this number of 1's.
For eg:
Input array: 1 0 0 1 0 0 1
Output: 6
Explanation:
If you choose a window [1,5], your array becomes,
1 1 1 0 1 1 1
which gives the total number of 1's now 6. So, your program should output the number 6, i.e. the maximum number of 1's after choosing a window.
Assume the numbers 1 through n are stored in a binary tree T. For the pre-
order, postorder and inorder traversals the output of a preorder
traversal of T with 5 nodes can be something like 2; 3; 1; 5; 4. We can think of
this output as the \preorder traversal signature" of the tree. Clearly, we can do
the same for both the postorder and inorder traversals.
a. Is the preorder traversal signature of a tree T unique? That is, are there
two trees storing the numbers 1 through n with the same preorder traversal
signature? How about the postorder traversal signature? the inorder traversal
signature? If your answer is yes to any of these questions, provide an expla-
nation.
Box stacking problem with boxes having k dimension, find max height of stack
Box stacking problem with variation of boxes having K DIMENSIONS , find the max height of stack of boxes
Find the permutation of a given string using dynamic programming . Try to do with the best possible time complexity and space complexity .
// You are given a rectangular grid of binary pixels that can be black or white.
// Some of the pixels may be black, but you don't initially know how many or
// where.
//
// Given a starting point (x,y), fill (i.e. make black) the region the pixel is
// in.
. . . . . . . . . . . . . . . . . . . .
. X X X . . X X X . . X X X . . X X X .
. X * X X X X . X . . X X X X X X X X .
. X . . . . . . X . -- > . X X X X X X X X .
. X . . . . . . X . . X X X X X X X X .
. X X X X X X X X . . X X X X X X X X .
. . . . . . . . . . . . . . . . . . . .
* . . . . . . . . . X X X X X X X X X X
. X X X . . X X X . X X X X X X X X X X
. X . X X X X . X . X X . X X X X . X X
. X . . . . . . X . --> X X . . . . . . X X
. X . . . . . . X . X X . . . . . . X X
. X X X X X X X X . X X X X X X X X X X
. . . . . . . . . . X X X X X X X X X X
See the correct drawing here: https://stackoverflow.com/questions/26079328/given-a-starting-point-x-y-fill-the-region-in-a-grid-the-pixel-is-located
What are your strengths?
Describe your two best projects
n mice are playing in the desert, when one of them notices some hawks flying in the sky. It alerts the other mice who now realize that the hawks are going to attack them very soon. They are scared and want to get inside holes to ensure their safety.
Mice and holes are placed on a straight line. There are m holes on this line. Each hole can accommodate only 1 mouse. A mouse can either stay at its position, or move one step right from x to x+1, or move one step left from x to x-1. Any of these movements takes 1 minute.
Assign mice to holes so that the time required for all the mice to move inside the holes is minimized.
Input Format
The first line contains an integer T, the number of test cases. This is followed by T blocks of input:
First line contains 2 positive integers n and m separated by a single space.
Next line contains n space separated integers, denoting the positions of the mice.
Next line contains m space separated integers, denoting the positions of the holes.
Note: No two holes have the same position.
Output Format
For each testcase, print the minimum time taken by all the mice to reach inside the holes.
Constraints
1 ≤ T ≤ 17
1 ≤ n ≤ 131072
1 ≤ m ≤ 131072
n ≤ m
-108 ≤ mouse[i] ≤ 108
-108 ≤ hole[j] ≤ 108
Sample Input
1
3 4
2 0 -4
3 1 2 -1
Sample Output
3
Explanation
One possible solution is :
Assign mouse at position x=-4 to hole at position x=-1 -> 3 minutes
Assign mouse at postion x=2 to hole at position x=2 -> 0 minutes
Assign mouse at postion x=0 to hole at postion x=3 -> 3 minutes
So the answer is 3, after 3 minutes all of the mice are in the holes.
non recursive method to calculate height of the binary tree.
you have a dictionary which will return true if the word is present in it otherwise false. You have a string "ABC", check if anagram of "ABC" is present or not. the condition was not to generate the all the anagram of ABC. (Assumption: you can store the dictionary in trie or hashmap (any data structure) and no need to implement the dictionary)
An array of size n is given. The array contains digits from 0 to 9. I had to generate the maximum number using the digits in the array such that it is divisible by 2, 3 and 5
eg: 1 array = 18760, output must be: 8160
eg: 2 array = 7776, output must be: “no number can be formed”
Given a set of entries, each containing a time index and a int count value,
ie
class Entry
{
time:int
count:int
}
write a function that will give the time interval with the highest count together,
ie,
if we had entries
100, 2
100, 1
110, 10
200, 4
1000, 3
1200, 8
and we ran something like
int highestInterval(int interval_range)
highestInterval( 50 )
it would return 100, because in 100-150, you have counts 2, 1, and 10.
I managed to get a O(n^2) solution for it, but I think theres a better solution. I think it might have to do with some preprocessing of the interval buckets, but I can't figure out the solution.
Components of computer systems often have dependencies -- other components that must be installed before they will function properly. These dependencies are frequently shared by multiple components. For example, both the TELNET client program and the FTP client program require that the TCP/IP networking software be installed before they can operate. If you install TCP/IP and the TELNET client program, and later decide to add the FTP client program, you do not need to reinstall TCP/IP.
For some components it would not be a problem if the components on which they depended were reinstalled; it would just waste some resources. But for others, like TCP/IP, some component configuration may be destroyed if the component was reinstalled.
It is useful to be able to remove components that are no longer needed. When this is done, components that only support the removed component may also be removed, freeing up disk space, memory, and other resources. But a supporting component, not explicitly installed, may be removed only if all components which depend on it are also removed. For example, removing the FTP client program and TCP/IP would mean the TELNET client program, which was not removed, would no longer operate. Likewise, removing TCP/IP by itself would cause the failure of both the TELNET and the FTP client programs. Also if we installed TCP/IP to support our own development, then installed the TELNET client (which depends on TCP/IP) and then still later removed the TELNET client, we would not want TCP/IP to be removed.
Write a program to automate the process of adding and removing components. To do this we will maintain a record of installed components and component dependencies. A component can be installed explicitly in response to a command (unless it is already installed), or implicitly if it is needed for some other component being installed. Likewise, a component, not explicitly installed, can be explicitly removed in response to a command (if it is not needed to support other components) or implicitly removed if it is no longer needed to support another component.
I found a reference to this problem online.. Check this for i/o details. This is the exact same problem
http://www.cs.cornell.edu/Info/Courses/Spring-98/CS211/assgts/assgt3/assgt3.pdf
Write a program to find first 20 elements with high density
Hi I wanted to know what I should prepare for an in person interview with amazon for the post of cloud support associate(AWS team)?
We have 'n' patients and 'm' problems. The problems are of boolean type. Eg diabetes problem would be 'T' if a patient has it or 'F' otherwise. Suggest the data structure you would store this scenario on?
Q: We have a set of problems {diabetes, liver disease, kidney disease} find all the patients who have at least the 3 problems from the set.
The number of patients can be huge (n).
The number of problems not comparatively huge (m).
Write a program to calculate height of a binary tree non - recursively. USE ONLY STACK , not using BFS.
Then he asked to implement it for n-ary tree.
Merge two sorted linked list
Design a stack using queue(s)
Design a valet parking system. Requirements of the valet parking system should be:
1. Customer are given a ticket that they can use to redeem to get their vehicle back
2. Parking spots come in three sizes, small, med, large
3. Thee types of vehicles, small, med, large
-a small vehicle can park in a small, medium, and large spot
-a medium vehicle can park in a medium and large spot
-a large vehicle can park in a large spot
Suppose you want improve the performance of search queries, using a cache. Each search queries is in form of a string and returns a list of ad id's in the form of longs.
Design a class with the appropriate data structure(s) that can manage a cache of search queries.
Say you have a string:
"Thisisasentence"
How would you separate the string into separate words, return either the sentence with spaces or as a list/array where each entry is a word
/* In "the 100 game," two players take turns adding, to a running
total, any integer from 1..10. The player who first causes the running
total to reach or exceed 100 wins.
What if we change the game so that players cannot re-use integers?
For example, if two players might take turns drawing from a common pool of numbers
of 1..15 without replacement until they reach a total >= 100. This problem is
to write a program that determines which player would win with ideal play.
Write a procedure, "Boolean canIWin(int maxChoosableInteger, int desiredTotal)",
which returns true if the first player to move can force a win with optimal play.
Your priority should be programmer efficiency; don't focus on minimizing
either space or time complexity.
*/
Boolean canIWin(int maxChoosableInteger, int desiredTotal) {
// Implementation here. Write yours
}
Check if tree is BST.
We have a char array and we need to reverse it. say Char Array is “Northern California USA”, need to print “USA California Northern”. Can’t use any other data structures or buffer. Can only use a char temp.
Find the kth minimum element into binary search.
We have array of strings. Go through each element of array and eliminate duplicates if any string is having. You have to save in the same array.
How do a free() knows how much memory has to be free.Suppose
int *p=(int*)malloc(sizeof(int)*100);
after some operation,
free(p);
Now how free() function knows from where to where memory has to be free?
Write test cases for one command from each category(db related):
DDL command
DML command
and also, for
Select command
How would you implement virtual functions in C
How would you implement virtual functions in C?
How would you access private data member in a class? This class is defined in a library which you cannot modify. There are no friend functions.
How to implement virtual functions in C?
Write a method that takes an int as input and outputs an int with the digits of the input in reverse, i.e. 12345 -> 54321.
Write a method that takes an int as an input and outputs the digits in reverse, i.e. 12345 -> 54321.
Write a function to determine if a binary tree is a true binary search tree and give the average performance of the function.
Design an elevator system for a high rise building.
Design an alarm clock.
A Load Balancer has the following functions:
getHost()
addHost(String)
removeHost(String)Implement these functions using any data structure you wish. Also indicate the average performance for each function and what you expect to be its call count in a typical system with respect to each other of the three functions. In other words, how often do you expect getHost() to be called compared to addHost(...)?
Constraints:
Hosts are unique.
getHost() returns a random host from the host group
3.There is a NXM grid of pixels,and each pixel is represented by 3 bits,1 each for R,G and B color values.You are given the address of beginning of grid in a character pointer,and a position x,y on the grid.You have to change that positions bits to some other given bits.
int a ;
int main()
{
printf("%u\n",&a);}
what will be the o/p of the above code if we run it 5 times, will it be same every time or not?
Given an input n, find the smallest number x such that x % n = 0 and sum of the digits in x is equal to n.
Note: x is so large even long long int can't keep it.
It is obvious that find the sum of digits using (x/10) gives timeout, so how can its complexity be reduced.
write a function for a BST to implement best case search.If exact search key not available in BST then return best suited key.Ex- if a tree has keys 21 15 26 30 55 7 and if my search key is 25 then this function should return 26.
Write a program to find the smallest number that can be formed by 0 and 9 which is divisible by a given number.
For example, if given number is 3 output should be 9,
if given number is 2 output is 90,
if given number is 10 output is 90,
Write a program to find the smallest number that can be formed by 0 and 9 which is divisible by a given number.
For example, if given number is 3 output should be 9,
if given number is 2 output is 90,
if given number is 10 output is 90,
if given number is 7 output is 10^23.
Suppose that each row of an n x n array A consists of 1's and D's such that, in any
row i of A, all the 1's come before any D's in that row. Suppose further that the
number of 1's in row i is at least the number in row i+ 1, for i= 0, 1, ... .n - 2.
Assuming A is already in memory, describe a method running in O(n) time (not
O(n2) time) for counting the number of 1's in the array A.
We have two strings A and B with the same super set of characters. We need to change these strings to obtain two equal strings. In each move we can perform one of the following operations:
1- swap two consecutive characters of a string
2- swap the first and the last characters of a string
A move can be performed on either string.
What is the minimum number of moves that we need in order to obtain two equal strings?
Input Format and Constraints:
The first and the second line of the input contains two strings A and B. It is guaranteed that the superset their characters are equal.
1 <= length(A) = length(B) <= 2000
All the input characters are between 'a' and 'z'
Output Format:
Print the minimum number of moves to the only line of the output
Sample input:
aab
baa
Sample output:
1
Explanation:
Swap the first and last character of the string aab to convert it to baa. The two strings are now equal.
Difference between a crash and exception.
Difference between macros and inline functions.
Mfc: message maps and virtual functions.
Different calling convention.
Late n early binding...
Garbage collector algorithm. When gc will fail to clean the memory.
How to know heap size, crash dump analysis, What is a stack n how to know stack memory size.
Commands in windbg.
Questions on Critical section, mutex, semaphores. Can we use mutex in single process and how?
Working of MSIL and JIT COMPILER.
Can a C# code, use c++ code and call kernel functions like createfile.
Areas: dot net, oops, operating systems, thread synchronization.
Difference in execution steps of c++ and c# code
How to impliment Google map
Data Structure and algorithm.
1. Zoom in/out
2. horizontal/ vertical.
Assumtion - all the image of earth with pixel\Any other assumption is allowed
How google map implemented ? zoom in , zoom out, moving horizontal and moving vertically.
Give data Structure and algorithm.
Given all the data from satellite which revolve around earth in spiral way.
Given ten million numbers, each having 11 bits, find the most time efficient way to sort the numbers.
Given an array and a number, find two integers that sums to the given number.
How to test a website which is selling shoes?
Given a array
{{ 4,7,3,6,7}}
construct a triangle like
{{81}}
{{40,41}}
{{21,19,22}}
{{11,10,9,13}}
{{ 4,7,3,6,7}}
Find the largest sum contiguous sub array. The length of the returned sub array must be at least of length 2.
Given an unsorted array of ints,sort the shortest sub-array which results in sorting of the whole array.
Ex:
i/p: [-1,0,4,3,2,1,7,8,9]
By sorting sub array [4,3,2,1] the whole Array is sorted.
i/p: [10, 15, 20, 30, 25, 40, 35, 45, 50, 60]
By sorting sub array [30, 25, 40, 35] the whole Array is sorted.
i/p: [-1,0,4,3,2,1,7,8,9,-2]
Shortest sub-arry to be sorted is [-1,0,4,3,2,1,7,8,9,-2]
Given a Tree (binary and unbalanced)
Find all the nodes in that tree which are 'n' levels up the leaf node...
Eg:
A->root
A.left=B
A.right=C
B.left=D
B.right=E
C.right=F
D.right=G
then
if 'n' as described in the above problem statement, is say n=2
then
answer should be :
B(2 nodes up from G), A(2 nodes up from E & F)
hence ans is B,A
My Algo was;
1)Perform a DFS (left,middle, right)
2) when leaf node is encountered.. just move the stack pointer (without poping or jsut coy the stack of DFS to another stack and perform a real time pop operation) by 'n' times and then just print the node which it encounters.
code:
int n=2;
Stack treeStack = new Stack();
function find(){
treeStack .push(rootnode);
performDFS();
}
function performDFS(){
if(currnetnode.left==null && currentnode.right==null){
// this is a leaf node.
Stack tmpStack=copyStack(treeStack);
// hard coded logic(two pop operations) without using a loop since i am usnig n=2 in //this example
tmpStack.pop(); // pop 1st element
element = tmpStack.pop(); // print the 2nd element
print(element);
}
if(currnetnode.left!=null)
treestack.push(currentnode.left);
if(currnetnode.right!=null)
tree.stack.push(currentnode.right);
}
Problem Link:https://code.google.com/codejam/contest/4214486/dashboard#s=p1
At new years party there is a pyramidal arrangement of glasses for wine. For example, at the top level, there would just be one glass, at the second level there would be three, then 6 and then 10 and so on and so forth like the following image
.
The glasses are numbered using 2 numbers, L and N. L represents the level of the glass and N represents the number in that level. Numbers in a given level are as follows:
Level 1:
1
Level 2:
1
2 3
Level 3:
1
2 3
4 5 6
Level 4:
1
2 3
4 5 6
7 8 9 10
Each glass can hold 250ml of wine. The bartender comes and starts pouring wine in the top glass(The glass numbered L = 1 and N = 1) from bottles each of capacity 750ml.
As wine is poured in the glasses, once a glass gets full, it overflows equally into the 3 glasses on the next level below it and touching it, without any wine being spilled outside. It doesn't overflow to the glasses on the same level beside it. It also doesn't overflow to the any level below next level (directly).
For example: When the glass of L = 2 and N = 2 overflows, the water will overflow to glasses of L = 3 and N = 2, 4, 5.
Once that the bartender is done pouring B bottles, figure out how much quantity in ml of wine is present in the glass on level L with glass number N.
Input
The first line of the input gives the number of test cases, T. T test cases follow. Each test case consists of three integers, B, L, N, B is the number of bottles the bartender pours and L is the glass level in the pyramid and N is the number of the glass in that level.
Output
For each test case, output one line containing "Case #x: y", where x is the test case number (starting from 1) and y is the quantity of wine in ml in that glass.
Given a graph where every two nodes are either friends or enemies with each other. Find a way to go from one node to the other.
Restrictions:
1) You can also travel from one node to next if they are friends with each other
2) You have some “magic potions”. You can convert an enemy path to a friend path with a magic potion.
I know this can be solved easily using dfs or bfs but i want to know the time complexity of each approach
There are two string pattern P and searching Expression Ex.. Ex is regular expression contains only # which stand for any character latest one length..
P:- ABABABA Ex:- A#B#A P and Ex are similar so its true.
example2. P: ABACBCB Ex:- A#B result:- true
Example:- P: ABCABCCE Ex:-A#C# result:- true, as P contains the expression as Ex
P: ABCABCCE Ex:-A#C false: P is doesnot contains the express like A#C
# --- means at least one or more character. In java language you have write the algorthim
There are two string pattern P and searching Expression Ex..
Ex is regular expression contains only # which stand for any character latest one length..
P:- ABABABA
Ex:- A#B#A
P and Ex are similar so its true.
example2.
P: ABACBCB
Ex:- A#B
result:- true
Example:-
P: ABCABCCE
Ex:-A#C#
result:- true, as P contains the expression as Ex
P: ABCABCCE
Ex:-A#C
false: P is doesnot contains the express like A#C
#--- means at least one or more character.
There are two string pattern P and searching Expression Ex..
Ex is regular expression contains only # which stand for any character latest one length..
P:- ABABABA
Ex:- A#B#A
P and Ex are similar so its true.
example2.
P: ABACBCB
Ex:- A#B
result:- true
Example:-
P: ABCABCCE
Ex:-A#C
false: P is doesnot contains the express like A#C
#--- means at least one or more character.
What is the diffenrce between join() and wait()?
What is sleep(). Which method releases the lock?
How can we implement asynchronous call in Java? Say I want to query Google but don’t want to use all the urls want to use later. How can we do that?
Whats the difference between quick sort and merge sort? Which one to use? Do we need file sorted before merge sort?
string x = "1..5,8,11..14,18,20,26..29"
string y = "1,2,3,4,5,8,11,12,13,14,18,20,26,27,28,29"
Write a C++ program to expand a given string x to y.
A certain language uses a set of characters from a-z but not in the same sequence as in english.
Now, words from the language appear in pair to you. e.g. LMOSS,NMOSS which implies that N comes after L, but not necessarily immediately after L. Similary, other words like{NMORR,TMORR}, { KSINN, KXINN }are also available.
What should be the data structure which should be used so that we can find out the character sequence in this language.
How to test a cheeseburger?
How long it will take to download a file containing all words of English dictionary on to the RAM
a music file is downloaded to your computer and you are listening a music you put a pause and you are going to somewhere and you came back and
you want to listen a music again and it is not working how do you trouble shoot and debug the problem?
We are given an unsorted array of n^2 arbitrary numbers, and we must output an n x n matrix of all the inputs such that all the rows and columns are sorted. For example, suppose n=3, n^2=9, and the 9 numbers are just the integers {1,2,...,9}
Possible ouputs include:
1 4 7 1 3 52 5 8 2 4 63 6 9 7 8 9Show how to sort this array with a Ω(n^2log n) lower bound.
Given an array of integers, but instead of all integers having the same length each can have a different number of bits. For example, the numbers 0 or 1 have 1 bit, 2, 3 have 2 bits, 4,5,6,7 have 3 bits. The TOTAL number of bits of all the integers in the array is n. Describe how to sort the array in O(n) time.
What is memory alignment in terms of compiler
what are types of memory issues one faces
Write a program to find 2 complement of number
How can we divide a large file between multi threads to process it? If we are running a multi threaded application and input is a large file and we have to provide each thread a part of the file to make it fast. How we can achieve it in java?
Mice and holes are placed in a straight line. There are n holes on this line. Each hole can accomodate only 1 mouse. A mouse can stay at his position, move one step right from x to x+1, or move one step left from x to x−1. Any of these moves consumes 1 minute.
Assign mice to holes so that the time when the last mouse gets inside a hole is minimized.
for example if there are 3 mice positions of mice are:
4 -4 2
positions of holes are:
4 0 5
the answer should be 4
because:
Assign mouse at position x=4 to hole at position x=4 : Time taken is 0 minutes
Assign mouse at postion x=-4 to hole at position x=0 : Time taken is 4 minutes
Assign mouse at postion x=2 to hole at postion x=5 : Time taken is 3 minutes
After 4 minutes all of the mice are in the holes.
Design an algorithm that, given a set S of n integers and another integer x,
determines whether or not there exist k (n>k>2) elements in S whose sum is
exactly x. Please give the running time of your algorithm
How can we use union find algorithm for finding the path between two points in a Maze
If we have all the variables and methods are as static. So would that class be thread safe?
Judgement Day
Skynet has figured out a way to take over the world. It will keep producing robots and molecular assemblers until it has converted all matter for its own purpose. Robots work to produce more robots and molecular assemblers. Molecular assemblers convert matter into programmable matter to be used to produce more robots and molecular assemblers.
Initial Info On day 0, Skynet started with 3 robots, 1 molecular assembler and 0 units of programmable matter.
On day i (i>0), robots produced can be calculated as the sum of the robots produced on the previous day and thrice the units of programmable matter produced on the previous day.
On day i, number of molecular assemblers produced can be calculated as the sum of robots produced on the previous day and twice the units of programmable matter produced on the previous day.
On day i, the units of programmable matter produced can be calculated as five times the number of molecular assemblers produced on the previous day.
How many robots, molecular assemblers and units of programmable matter will be produced on the Judgement Day (day n)?
Input/Output Specifications
Input format: Two integers x and y (1<=x,y<=10^6) such that the judgement day falls on day n = x*y.
Output format: Since the number of robots, molecular assemblers and units of programmable matter grows very rapidly, we want you to output them modulo 1000000007.
The output should be a string having the following format: R#M#P, where - R is the number of robots produced on judgement day modulo 1000000007 - M is the number of molecular assemblers produced on judgement day modulo 1000000007 - P is the number of units of programmable matter produced on judgement day modulo 1000000007
Distributing Medals It's the medal distribution ceremony. 10^6 police officers, numbered from 1 to 10^6, are standing in a line. There are N (1<=N<=1000) iterations of medal distribution. In iteration i (0 < = i < N), count[i] ( 1 < = count[i] < = 100) medals are given to all officers from from[i] to to[i] ( 1 < = from[i] < = to[i] < = 10^6 )
If we sum up the number of medals received starting from the first officer, who would be the first officer for which the cumulative sum exceeds a given medal count THRESHOLD ( 1 < = THRESHOLD < = 10^9 )?
Input/Output Specifications Input format:
You are given 5 inputs:
input1 = N, the number of iterations
input2 = count, the array of medal counts in each iteration
input3 = from, the array of starting indices in each iteration
input4 = to, the array of ending indices in each iteration
input5 = THRESHOLD, the medal count threshold
Output format:
An integer, representing the number of the first officer such that the cumulative sum of medals starting from the first officer upto this officer exceeds THRESHOLD. The output should be -1 if such an officer does not exist
Judgement Day
Skynet has figured out a way to take over the world. It will keep producing robots and molecular assemblers until it has converted all matter for its own purpose. Robots work to produce more robots and molecular assemblers. Molecular assemblers convert matter into programmable matter to be used to produce more robots and molecular assemblers.
Initial Info On day 0, Skynet started with 3 robots, 1 molecular assembler and 0 units of programmable matter.
On day i (i>0), robots produced can be calculated as the sum of the robots produced on the previous day and thrice the units of programmable matter produced on the previous day.
On day i, number of molecular assemblers produced can be calculated as the sum of robots produced on the previous day and twice the units of programmable matter produced on the previous day.
On day i, the units of programmable matter produced can be calculated as five times the number of molecular assemblers produced on the previous day.
How many robots, molecular assemblers and units of programmable matter will be produced on the Judgement Day (day n)?
Input/Output Specifications
Input format: Two integers x and y (1<=x,y<=10^6) such that the judgement day falls on day n = x*y.
Output format: Since the number of robots, molecular assemblers and units of programmable matter grows very rapidly, we want you to output them modulo 1000000007.
The output should be a string having the following format: R#M#P, where - R is the number of robots produced on judgement day modulo 1000000007 - M is the number of molecular assemblers produced on judgement day modulo 1000000007 - P is the number of units of programmable matter produced on judgement day modulo 1000000007
In the following equation x, y, and n are positive integers.
1/x + 1/y = 1/n
For n = 4 there are exactly three distinct solutions:
1/5 + 1/20 = 1/4
1/6 + 1/12 = 1/4
1/8 + 1/8 = 1/4
What is the least value of n for which the number of distinct solutions exceeds one-thousand?
hiii...i have a question..."how to find duplicate in large file"
Write a c program to check number(0123456789) in array of string is valid or not
number is valid only if it is number or number padded with right space
for example char ex[10];
0123456789 valid
012345678a invalid
0123a56789 invalid
01234 invalid
012345678 valid
01234567 valid
12345 invalid
1234 678 invalid
123 4 5678 invalid
There is an array of 3-tuple, in the form of (a, 1, 5). The first element in the tuple is the id, the second and third elements are both integers, and the third is always larger than or equal to the second. Assume that the array is sorted based on the second element of the tuple. Write a function that breaks each of the 3-tuple into two 2-tuples like (a, 1) and (a, 5), and sort them according to the integer.
E.g. given (a, 1, 5), (b, 2, 4), (c, 7, 8), output (a, 1), (b, 2), (b, 4), (a, 5), (c, 7), (c, 8).
Write a java program read 3 numbers and line length make triangle..find whether triangle is isosceles or equilateral triangle,also find out rightangle triangle?
Write a java program multiply two 10-digit numbers and the number is very large number(10,000) ten thousand digits,don't use any built-in functions?
You and your friends are pilots in the Clone army.You are facing the aerial fleet of the Droid army.Droid planes move while maintaining a long line so that their shields interact making it impossible to shoot down planes in the middle of the line.Thus,your only option is to keep shooting down planes at the edges of the line.
You and your friend have decided to make a game of it.Each Droid plane has an importance level IMP[i].Since the droid planes don't advertise their importance levels, both of you must follow a mixed strategy and shoot down either the first plane or the last plane with 50% chance each.If there is a single plane,the shooter with the turn will shoot it down for sure.The two of you take turns to shoot down enemy planes.You have the first turn.What is the expected sum of importance levels you will shoot down?
Input format:
# The number of droid planes
input1=N(1<=N<=1000)
# An array containing the importance levels of droid planes.
input2=IMP(for 0<i<=N,1<=IMP[i]<=100)
Output format:
A string containing your expected sum of importance levels of shot down planes,rounded to 3 places of decimal.
Example:
Input:
2
10 20
Output:
15.000
There is a test automation running and fails 14%, say 1/7 times? How you will debug? There is no code change or test code change.
There are several words in a file. Get the occurrence of every word and sort it based on the occurrence, if more than one word is having same occurrence than sort it alphabetically.
We have one single linked list. How we’ll travers it that we reach till second last (n-1) node. If we want to reach till (n\2) node.
In a directory we have several big log files? How u’ll find it how many number of lines are there in file? Aggregated count for all the files. What is if multiple threads are using those files? How will u be assigning files to them? What if one file size is way bigger than others.
There are a large number of leaves eaten by caterpillars. There are 'K"' caterpillars which jump onto the leaves in a pre-determined sequence. All caterpillars start at position 0 and jump onto the leaves at positions 1,2,3...,N. Note that there is no leaf at position 0.
Each caterpillar has an associated 'jump-number'. Let the jump-number of the i-th caterpillar be A [i]. A caterpillar with jump number 7 keeps eating leaves in the order 1,241,3*1,... till it reaches the end of the leaves - i.e, it eats the leaves at the positions which are multiples of /'.
Given a set 'A' of 'IC elements. 'e<=15.,. 'N'<=109, we need to determine the number of uneaten leaves.
Input Format:
N -number of leaves
A - Given array of integers
Output Format:
An integer denoting the number of uneaten leaves.
Sample Input:
N = 10
A = [2,4,5]
Sample Output:
4
Explanation
1,3,7,9 are the leaves which are never eaten. All leaves which are multiples of 2, 4, and 5 have been eaten.
Java Code:
public class Solution {
//need to complete the function below
static int countUneatenLeave(int N, int[] A {
}
public static void main(String[] args) throws IOException {
Scanner in = new Scanner(System.in);
final String fileName = System.getenv("OUTPUT_PATH");
BufferedWriter bw = new BufferedWriter(new FileWriter(fileName));
int res;
int _N;
_N = Integer.parseInt(in.nextLine());
int _A_size = Integer.parseInt(in.nextLine());
int[] _A = new int(_A_size];
int _A_item;
for(int _A_i = 0; _A_i < _A_size; _A_i++) {
_A_item = Integer.parseInt(in.nextLine());
_A[_A_i] = _A_item;
}
res = countUneatenLeaves(_N,_A);
bw.write(String.valueOf(res));
bw.newLine();
bw.close();
}
}There are a large number of leaves eaten by caterpillars. There are 'K"' caterpillars which jump onto the leaves in a pre-determined sequence. All caterpillars start at position 0 and jump onto the leaves at positions 1,2,3...,N. Note that there is no leaf at position 0. Each caterpillar has an associated 'jump-number'. Let the jump-number of the i-th caterpillar be A [i]. A caterpillar with jump number 7 keeps eating leaves in the order 1,241,3*1,... till it reaches the end of the leaves - i.e, it eats the leaves at the positions which are multiples of /'. Given a set 'A' of 'IC elements. 'e<=15.,. 'N'<=109, we need to determine the number of uneaten leaves. Input Format: N -number of leaves A - Given array of integers Output Format: An integer denoting the number of uneaten leaves. Sample Input: N = 10 A = [2,4,5] Sample Output: 4 Explanation 1,3,7,9 are the leaves which are never eaten. All leaves which are multiples of 2, 4, and 5 have been eaten.
Java Code
public class Solution {
//need to complete the function below
static int countUneatenLeave(int N, int[] A {
}
public static void main(String[] args) throws IOException {
Scanner in = new Scanner(System.in);
final String fileName = System.getenv("OUTPUT_PATH");
BufferedWriter bw = new BufferedWriter(new FileWriter(fileName));
int res;
int _N;
_N = Integer.parseInt(in.nextLine());
int _A_size = Integer.parseInt(in.nextLine());
int[] _A = new int(_A_size];
int _A_item;
for(int _A_i = 0; _A_i < _A_size; _A_i++) {
_A_item = Integer.parseInt(in.nextLine());
_A[_A_i] = _A_item;
}
res = countUneatenLeaves(_N,_A);
bw.write(String.valueOf(res));
bw.newLine();
bw.close();
}
}
How to implement Dictionary, I gave solution using Tries then they asked how to implement using HashMap.
> What is the advantage of HashMap over Tries.
> What is the advantage of Tries over HashMap.
> How to implement dictionary using HashMap so that when i press a character it will list all the words starting with that character.
Given two Binary Tree, need to check both are same or not(Without using recursion). Extend the solution for Tree.
Knight movement on a chess board...
Given any source point and destination point. Need to find whether Knight can move to destination or not.
If yes, Then what would be the minimum movement.
Extended Question : Extend the solution when chess size is infinite.
PS : Had to solve without recursion
Design a system for elevator and write all the classes and interfaces and show the relationships in between them.
What is out in System.out.println(). How can we redirect System.out.println to file than showing on console? Say we have
System.out.println("Hello World!!"). We want "Hello World!!" written to file than showing on console.
Write code for tree traversal. If we have cyclic dependency in tree, say child is pointing to parent, how can we traverse it?
You stand in one corner of a large room, and your assistant is in its opposite corner. In front of the assistant is a 4-corner table, with a coin in each of the 4 corners. Your objective is to get the coins to be all heads or all tails. When that happens, the coins start jumping up and down; so, you'll know for sure when it happens. What you can do is to tell your assistant: (a) flip one coin; (b) flip two coins on a side of the table; (c) flip two coins on a diagonal of the table. You can't tell the assistant which coin, which side, or which diagonal to use. You can either think of your assistant as being extremely dumb, or that the table is being constantly rotated by external forces. What is the sequence of commands that you should give to your assistant to make sure the coins start jumping up and down?
Find the k-complimentary pairs of an Array A.
A[0] = 1;
A[1] = 8;
A[2] = -3;
A[3] = 0;
A[4] = 1;
A[5] = 3;
A[6] = -2;
A[7] = 4;
A[8] = 5;
k = 6 would yield a return value of 7.
(0,8)(1,6)(4,8)(5,5)(6,1),(8,0)(8,4)
Time complexity should be O(n log n) or better
Space complexity O(n).
It was on codility, the default of which said "write your code in C++ 11, and as an example of an include has "#include <algorithm>". STL is fair game. The template showing how the function should be written used std::vector<int>.
Given a start position and an target position on the grid. You can move up,down,left,right from one node to another adjacent one on the grid. However there are some walls on the grid that you cannot pass. Now find the shortest path from the start to the target.
(This is easy done by BFS)
Extend. If you can remove three walls, then what is the shortest path from start to the target. (I have no ideal except for enumerate all the possibility of three walls. It must be the silly solution.) Does anyone have any idea?
find the value of n in a 2 power n number....optimized answer...
find the value of n in a 2 power n number....optimized answer...
Write a recursive method to get the multiplication of two numbers such that there are minimum number of addition operations.
Consider a MxN matrix. You are given a start element(index) and an end element. The question is to find a path from start to end. Please note that in some blocks 'X' is marked which means your path cannot go through that element. My solution was to have a tree with 4 nodes (top/left/right/bottom) and recursively check if there is a path from start to end.
Distributing Medals It's the medal distribution ceremony. 10^6 police officers, numbered from 1 to 10^6, are standing in a line. There are N (1<=N<=1000) iterations of medal distribution. In iteration i (0 < = i < N), count[i] ( 1 < = count[i] < = 100) medals are given to all officers from from[i] to to[i] ( 1 < = from[i] < = to[i] < = 10^6 )
If we sum up the number of medals received starting from the first officer, who would be the first officer for which the cumulative sum exceeds a given medal count THRESHOLD ( 1 < = THRESHOLD < = 10^9 )?
Input/Output Specifications Input format:
You are given 5 inputs:
input1 = N, the number of iterations
input2 = count, the array of medal counts in each iteration
input3 = from, the array of starting indices in each iteration
input4 = to, the array of ending indices in each iteration
input5 = THRESHOLD, the medal count threshold
Output format:
An integer, representing the number of the first officer such that the cumulative sum of medals starting from the first officer upto this officer exceeds THRESHOLD. The output should be -1 if such an officer does not exist.
Distributing Medals It's the medal distribution ceremony. 10^6 police officers, numbered from 1 to 10^6, are standing in a line. There are N (1<=N<=1000) iterations of medal distribution. In iteration i (0 < = i < N), count[i] ( 1 < = count[i] < = 100) medals are given to all officers from from[i] to to[i] ( 1 < = from[i] < = to[i] < = 10^6 )
If we sum up the number of medals received starting from the first officer, who would be the first officer for which the cumulative sum exceeds a given medal count THRESHOLD ( 1 < = THRESHOLD < = 10^9 )?
Input/Output Specifications Input format:
You are given 5 inputs:
input1 = N, the number of iterations
input2 = count, the array of medal counts in each iteration
input3 = from, the array of starting indices in each iteration
input4 = to, the array of ending indices in each iteration
input5 = THRESHOLD, the medal count threshold
Output format:
An integer, representing the number of the first officer such that the cumulative sum of medals starting from the first officer upto this officer exceeds THRESHOLD. The output should be -1 if such an officer does not exist.
How can you handle uncheckedexceptions globally in project?
There are 3 fields in a music list. number of requests, genre name, Index. And list can take upto 1000 entries. An user can search based in genre name, index and number of requests. index and genre name can be optional. Write test cases to get the list searched by user.
What is the most challenging part in ur carreer?
your manager wants 100% automation for a product. But it is not possible. what will you do?
write test cases for group chat?
Amazon site is slow. how will you troubleshoot ?
Function generates random numbers every 30 sec. once in a while it takes long time to generate. how will u Debug this?
There are 6 hosts and there are 6 machines in each host. Admin uses dice role to allocate machine to each user. Write test cases for dice role and machine allocation.
A function takes 2 inputs and do some computation and stores in cache. If result is already there, it doesn’t do computation and get the results from cache, otherwise it does some computation and get the results and stores in cache. Write test cases for this.
Given a Sorted integer array which is rotated N number of times. You have no idea what that N is. An element in the array can occur more for any number of time. Write a method to search the position of a given element. If there are more than one of the same element, return the position of the first element.
Given three arrays A,B,C containing unsorted numbers. Find three numbers a, b, c from each of array A, B, C such that |a-b|, |b-c| and |c-a| are minimum
Please provide as efficient code as you can.
Can you better than this ???
1. If we have 2 column in table, user id and date which user has logged in. How can we find the user id who has logged in most. means max number of time.
Recursively implement a function that returns boolean value by checking if a binary tree is binary search tree or not.
We need to make a string of size n. Each character of the string is either ‘R’, ‘B’ or ‘G’. In the final string there needs to be at least r number of ‘R’, at least b number of ‘B’ and at least g number of ‘G’ (such that r + g + b <= n). We need to find number of such strings possible.
For example,
n = 4, r = 1, b = 1, g = 1.
Output:
36
You are given two integer arrays A and B .
1<=i<=len(A) so i is iterator of array A
1<=j<=len(B) so j is iterator of array B
find all the pairs(i,j) such that : i < j and A[i]>B[j]
How does one application implement similar to DropBox? How can we Mmake sure they are in sync for files. How u’ll check for files are downloaded. How u’ll download files. What protocols u’ll use?
Given an array of positive and negative numbers(no zeroes),i have to arrange them in such a way that the positive and negative numbers should be arranged consecutively.The number of positive and negative numbers may not be equal i.e. if there is no positive number(or negative) left,then all the remaining negative numbers(or positive) are appended to the end of the array.The order is important i.e.if input array is { 2,-1,-3,-7,-8,9,5,-5,-7},then the output array should be {2,-1,9,-3,5,-7,-8,-5,-7}.The code is done in O(n) without using another array.I came up with a solution in which i chose 0 as pivot element and separate the numbers (using quicksort) but in this case the order is not preserved.
A hotel manager has to process n advance bookings of rooms for the next season. His hotel has k identifical rooms. Bookings contain
an arrival date and a departure date. He wants fo find out whether there are enough rooms in the hotel to satify the demand.
Design an algorithm that solves this problem in time O(n logn) . Hint:Consider the set off all arrivals and departures .
Sort the set and process it in sorted order.
Made in Merge Sort
Traveling Salesman Problem
Whats the time complexity of this code?
When I told him its O(N^3), he told me to look carefully, its O(N^2),
I dont know why? Any idea?
for (int i = 0; i < n-2; ++i)
{
//some code
for (int j = i+1; j < n-1; ++j)
{
//some code
for (int k = j+1; k < n; ++k)
{
//some code
}
}}
Define a class Marks as having the fields marks1, marks2, marks3 and maxMarks all of type int.
In the class Marks
- define a constructor of the class whch takes 3 ints as input and assigns them to marks1, marks2 and mark3 respectively. It aslo assigns the maximum of marks1, marks2 and marks3 to maxMarks.
- define a method getMaxMarks() which returns the maximum of marks1, marks2 and marks3.
- define a method isPass() which returns true if the average of marks1, marks2 and marks3 is at least 40.
Define a class StudentList which has the field allMarks(of type Marks[]). In the class, define the methods
- totalStudents() which returns the number of total students which is the number of objects in the array allMarks
- passCount() which returns the number of students who have passed.
Define a class Point having 2 fields x (int) and y (int) which represents a point (x,y)
Define a class Line having 2 Points, pt1 and pt2.
Define a class Quadrilateral having 4 Points, pt1, pt2, pt3 and pt4. The class also has the following functions
- getAllLines() which returns a Line[] consisting all 4 lines of the Quadrilateral. Note that the 4 lines of the quadrilateral will be pt1:pt2, pt2:pt3, pt3:pt4 and pt4:pt1
- longestSide() which return a Line that represents the longest the side of the Quadrilateral.
Also define the constructors for each class
Define a class Marks as having the fields marks1, marks2, marks3 and maxMarks all of type int.
In the class Marks
- define a constructor of the class whch takes 3 ints as input and assigns them to marks1, marks2 and mark3 respectively. It aslo assigns the maximum of marks1, marks2 and marks3 to maxMarks.
- define a method getMaxMarks() which returns the maximum of marks1, marks2 and marks3.
- define a method isPass() which returns true if the average of marks1, marks2 and marks3 is at least 40.
Define a class StudentList which has the field allMarks(of type Marks[]). In the class, define the methods
- totalStudents() which returns the number of total students which is the number of objects in the array allMarks
- passCount() which returns the number of students who have passed.
They conducted a hiring round and this was asked there ?
Hi friends This question was asked in recent hiring challenge at hackerearth , that is over now,Please discuss your strategies.I am not able to devise algorithm please provide some hints to solve it.
Pulkit is really good at maths. Recently, he came to know about a problem on matrices. Amazed by the problem he got, he asked Ashish the same problem. Ashish also being good at maths solved the problem within 5 minutes. Now, its your time to solve the problem.
You will be given n*m binary matrix. You need to tell if it is possible to delete a column such that after deleting that column, rows of the matrix will be unique. If yes than print "Yes" else print "No".
[Input]
First line contains an integer t denoting no.of test cases.
Next line contains 2 integers n and m denoting no.of rows and columns.
Next n line contains binary string of length m each.
[Output]
For each test case output "Yes" or "No".
[Constraints]
1<=t<=100
1<=n<=1000
2<=m<=1000
Sample Input (Plaintext Link)
2
3 3
101
000
100
2 2
11
11
Sample Output (Plaintext Link)
Yes
No
Given a 2-dimensional array with arbitrary sizes and contains random positive values, you are required to move from the first element [0][0] to the last element [n][n] using the path which will yield the maximum sum of all the elements traversed. You can only move right and down; NOT left and up.
How can we get square of a number without using * or carrot sign.
Write a query which return 5 persons who had spent most from a table and table contains customer id, product id and expenses. Customer id can be duplicate.
There is 3 text file, like file1.txt, file2.txt etc. Every file contains customer id, product id and expenses. Now write java code which will return 5 persons who spent most in these three files. Customer id can be duplicate all over files.
How can we get the square of a number without using * or carrot sign.
Design a Meeting Reminder Pop-up similar to one found on outlook.
Data Structure to be used and come up with classes.
JAVA:
Given an array say of length 1000; Pick up every value from every 20th index and store it in a separate array. Make sure to loop through all the elements in the array. Example: newArray1 = {0, 20, 40, 60, ..};
newArray2 = {1, 21,41, 61, ..};
Given an array say of length 1000; Pick up every value from every 20th index and store it in a separate array. Make sure to loop through all the elements in the array. Example: newArray1 = {0, 20, 40, 60, ..};
newArray2 = {1, 21,41, 61, ..};
Given a binary tree,Write a function to return all of the nodes from a given node and a given distance. The function has three parameters root, the given node and the given distance. For example
5
/\
4 7
/\
6 10
\
12
Calling the function F(root,7,1) will the return all the nodes from node 7 with the distance 1 which is 6,10,5
another example is F(root.7,2) will the return nodes 12,4
Write a function to return all of the nodes from a given node and a given distance. The function has three parameter root, the given node and the given distance. For example
5
/\
4 7
/\
6 10
\
12
Calling the function F(root,7,1) will the return all the nodes from node 7 with the distance 1 which is 6,10,5
another example is F(root.7,2) will the return nodes 12,4
Give a Binary tree, write a function to return all the nodes from a given with a given distance. The function has three parameters root of tree, a given node, a given distance. For example,
5
/\
4 7
/\
3 10
\
12
calling the function F(root,7,1) will return nodes 3,5,10
calling F(root,7,2) will return nodes 12,4
There is a compressed string eg. ”ab2c3”, the string has lowercase characters and numbers. We can uncompress the given string as follows: whenever we get a number “n” in the string, the portion of the string before the number will repeat “n” times. So in the above example, we get a 2, so string will become “ababc3”, now we get a 3, so final string will be “ababcababcababc”.
Given a compressed string and a number k, you have to output the k’th character in the uncompressed string.
1 <= length of string <= 1500
1 <= n <= 1000
1 <= k < 2^31
example:
input: ab2c3 10
output: c
Implement a function to return top rated movies in the network of movies reachable from the current movie.
* eg. A(Rating 1.2)
* / \
* B(2.4) C(3.6)
* \ /
* D(4.8)In the above example, edges represent similarity and the number is rating.
* getMovieRecommendations(A,2) should return C and D (sorting order doesn't matter so it can also return D and C)
* getMovieRecommendations(A,4) should return A, B, C, D (it can also return these in any order eg: B,C,D,A)
* getMovieRecommendations(A,1) should return D. Note distance from A to D doesn't matter, return the highest rated.
import java.util.ArrayList;
import java.util.List;
public class Movie {
private final int movieId;
private final float rating;
private List<Movie> similarMovies; // Similarity is bidirectional
public Movie(int movieId, float rating) {
this.movieId = movieId;
this.rating = rating;
similarMovies = new ArrayList<Movie>();
}
public int getId() {
return movieId;
}
public float getRating() {
return rating;
}
public void addSimilarMovie(Movie movie) {
similarMovies.add(movie);
movie.similarMovies.add(this);
}
public List<Movie> getSimilarMovies() {
return similarMovies;
}
/* *
* @param movie
* @param numTopRatedSimilarMovies
* number of movies we want to return
* @return List of top rated similar movies
*/
public static List<Movie> getMovieRecommendations(Movie movie, int numTopRatedSimilarMovies) {
// Implement me
return null;
}
}Given an array of positive and negative numbers, arrange them in an alternate fashion such that every positive number is followed by negative and vice-versa maintaining the order of appearance.
Number of positive and negative numbers need not be equal. If there are more positive numbers they appear at the end of the array. If there are more negative numbers, they too appear in the end of the array.*
Example:
Input: arr[] = {1, 2, 3, -4, -1, 4}
Output: arr[] = {-4, 1, -1, 2, 3, 4}
Input: arr[] = {-5, -2, 5, 2, 4, 7, 1, 8, 0, -8}
output: arr[] = {-5, 5, -2, 2, -8, 4, 7, 1, 8, 0}Limitations:
a) Use O(1) extra space
b) Time Complexity should be O(N)
c) Maintain the order of appearance of elements as in original array.
In a given string of 0s and 1s , if you flip only one 0 to 1 , what would be the longest contiguous string of 1s possible. e.g
{0 01 0 11010 0} the answer would be 4 and attained by flipping bit number 7 form 0 to 1 . Came up with O(n2) , expected was O(n)
On a very large rotated sorted array with one or more duplicates, find the index of a particular number: 20,30,30,45,60,60,5,17,17,19
How would you architect a client based recommendation feature(based on customer history) on product detail page?
Design Customers who viewed this also viewed that for an online shopping portal
. In an unsorted array of numbers that occurs an odd number of times except one that occurs an even number of times, find the number that occurs an even number of times
Design a thread safe hash table from ground up.
Follow up question: How do you design it without using any locks.
Given a doubly linked list, copy the list.
Edit:
Struct node{
node *pNext;
node *pPrev;
node *pRandom;
};
pRandom has connection to any random nodes.
Write a program to clone this list.
(To write in Objective-C; I will write the EXACT question)
Given a dictionary of words, return an array of the words whose match. (i.e. pattern "c.t" match with "cat", "cut", etc. because the dot notation stand for ANY character).
SUGGEST: use suffix tree, for(for()) is not a good solution.
Print the output of linked list in the reverse order without altering the actual linked list.
First try it without recursion and then with recursion
Original linked list A->B->C->D
Output should be DCBA
Algorithm to check whether given sequence is arithmetic progression or geometric progression
Algorithm to check whether given series is arithmetic progression or geometric progression
I want to make a graph problem that use object-oriented java.
Example: dijkstra,Kruskal
*
* *
* * *
* * * * write a program in java??
Table 1; transaction_id, price
Table 2: transaction_id, zipcode
Query to find the avg price per zipcode
Query to show zipcodes that have an avg price more than $5.
Ebay lowers its listing fee for one of the product ( bikes), and sees an increase in avg sales price. Explain why?
What is difference between Having and where clause?
what all design patterns are used in designing a shopping cart and explain?
How do you normalize shopping cart tables?
Password storage rather than storing in DB.
How the tables are stored(different tables structure)
Design a shopping cart.
package jp.co.worksap.global;
import java.util.NoSuchElementException;
/**
* The Queue class represents an immutable first-in-first-out (FIFO) queue of objects.
* @param <E>
*/
public class ImmutableQueue<E> {
/**
* requires default constructor.
*/
public ImmutableQueue() {
// modify this constructor if necessary, but do not remove default constructor
}
// add other constructors if necessary
/**
* Returns the queue that adds an item into the tail of this queue without modifying this queue.
* <pre>
* e.g.
* When this queue represents the queue (2, 1, 2, 2, 6) and we enqueue the value 4 into this queue,
* this method returns a new queue (2, 1, 2, 2, 6, 4)
* and this object still represents the queue (2, 1, 2, 2, 6) .
* </pre>
* If the element e is null, throws IllegalArgumentException.
* @param e
* @return
* @throws IllegalArgumentException
*/
public ImmutableQueue<E> enqueue(E e) {
return null;
}
/**
* Returns the queue that removes the object at the head of this queue without modifying this queue.
* <pre>
* e.g.
* When this queue represents the queue (7, 1, 3, 3, 5, 1) ,
* this method returns a new queue (1, 3, 3, 5, 1)
* and this object still represents the queue (7, 1, 3, 3, 5, 1) .
* </pre>
* If this queue is empty, throws java.util.NoSuchElementException.
* @return
* @throws java.util.NoSuchElementException
*/
public ImmutableQueue<E> dequeue() {
return null;
}
/**
* Looks at the object which is the head of this queue without removing it from the queue.
* <pre>
* e.g.
* When this queue represents the queue (7, 1, 3, 3, 5, 1),
* this method returns 7 and this object still represents the queue (7, 1, 3, 3, 5, 1)
* </pre>
* If the queue is empty, throws java.util.NoSuchElementException.
* @return
* @throws java.util.NoSuchElementException
*/
public E peek() {
return null;
}
/**
* Returns the number of objects in this queue.
* @return
*/
public int size() {
return -1;
}
}
Normally where singleton design pattern used in a project?
what is low level design and high level design in realtime java?
what are the top 10 coding standards/code reviews in java?
Spring following by default singleton scope..so if we are using clone() is there anything happend?if anyone knows please tell me the answer
Solve Travelling salesman problem using Iterative Deepening Search Algorithm.
Edit:
You have been given distance between each pair of cities and the number of cities
How to find non- common elements between two string arrays. Eg: String a[]={"a","b","c","d"};
String b[]={"b","c"};
O/p should be a,d
You have the following function:
F(m, n) = F(m-1, n-1) + F(m, n-1)
m, n - positive integer numbers > 0
F(1, n) = 1
F(m, 1) = 1
You need to write this function. The problem is that if x=1000000 and y=1000000, for instance, the number of recursive calls will be extremely large.
Consider a regular polygon with N vertices labelled 1..N. In how many ways can you draw K diagonals such that no two diagonals intersect at a point strictly inside the polygon? A diagonal is a line segment joining two non adjacent vertices of the polygon.
Input:
The first line contains the number of test cases T. Each of the next T lines contain two integers N and K.
Output:
Output T lines, one corresponding to each test case. Since the answer can be really huge, output it modulo 1000003.
Constraints:
1 <= T <= 10000
4 <= N <= 10^9
1 <= K <= N
Sample Input:
3
4 1
5 2
5 3
Sample Output:
2
5
0
Explanation:
For the first case, there are clearly 2 ways to draw 1 diagonal - 1 to 3, or 2 to 4. (Assuming the vertices are labelled 1..N in cyclic order).
For the third case, at most 2 non-intersecting diagonals can be drawn in a 5-gon, and so the answer is 0.
Question was very similar to this one
http://www.hackerearth.com/thoughtworks-hiring-challenge/algorithm/swap-it-2/
Bob loves sorting very much. He is always thinking of new ways to sort an array.His friend Ram gives him a challenging task.He gives Bob an array and an integer K .The challenge is to produce the lexicographical minimal array after at most K-swaps.Only consecutive pairs of elements can be swapped.Help Bob in returning the lexicographical minimal array possible after at most K-swaps.
Input: The first line contains an integer T i.e. the number of Test cases. T test cases follow. Each test case has 2 lines. The first line contains N(number of elements in array) and K(number of swaps).The second line contains n integers of the array.
Output: Print the lexicographical minimal array.
Constraints:
1<=T<=10
1<=N,K<=1000
1<=A[i]<=1000000
Sample Input (Plaintext Link)
2
3 2
5 3 1
5 3
8 9 11 2 1
Sample Output (Plaintext Link)
1 5 3
2 8 9 11 1
Explanation
After swap 1:
5 1 3
After swap 2:
1 5 3
{1,5,3} is lexicographically minimal than {5,1,3}
Example 2:
Swap 1: 8 9 2 11 1
Swap 2: 8 2 9 11 1
Swap 3: 2 8 9 11 1
You are given a list of items / combo_items with their price list.
And you are given list of items to buy.
Now you are asked to find which combination to buy so that it costs you minimum.
It doesnt matter if you are getting some extra items if it costs less.
Sr.No Price | Items/Combo_Items
1. 5 | Burger
2. 4 | French_Frice
3. 8 | Coldrink
4. 12 | Burger, French_Frice, Coldrink
5. 14 | Burger, Coldrink
Input Items to Buy:
Coldrink
Output(Sr.No)
3
Input Items to Buy:
Burger Coldrink
Output(Sr.No)
4
Input Items to Buy:
Burger French_Frice
Output(Sr.No)
1,2
Java runs on a "virtual" stack machine inside JVM, which has instruction of size of one byte (called byte-codes). How many instructions/bytecodes potentially can such a machine have?
PICK ONE OF THE CHOICES
256
Unlimited
2^32 for 32-bit machines
Depends on JVM version
In a multi-threaded application, many threads are trying to access the same
resource, say a global c ount, g. Threads are synchronized by the following code
(assume lock is a static int variable, initialized to 0 (unlocked state)):
if (lock) wait(); // It's already locked so wait(sleep) till someone wakes me up
else lock=1; // I locked it
/* Critical Section - Increment g */
lock = 0; // Lock released, so wakeup only one of other waiting threads, if any
What is the issue with this synchronization?
PICK ONE OF THE CHOICES
No issues – will work correctly
Works only on a uniprocessor system and would not work on multiprocessor system
Will not work on any system
Cannot say – need more data
A file of encoded message contains only numbers. Original message contains only lowercase letters and spaces. So character ‘a’ is mapped to 1 ‘b’ to 2 and so on till ‘z’ is mapped to 26. Given an input of numbers find out the number of ways you can decode it in original message. Eg. 123 can be decoded in 3 ways as 'abc', 'lc' or 'aw'
A file of encoded message contains only numbers. Original message contains only lowercase letters and spaces. So character ‘a’ is mapped to 1 ‘b’ to 2 and so on till ‘z’ is mapped to 26. Given an input of numbers find out the number of ways you can decode it in original message. Eg. 123 can be decoded in 3 ways as ‘abc’, ‘lc’ or ‘aw'
How will you design, and what data structure will you use for a contact list in a cell Phone. It should support insert/modify/delete/search functionality like that provided in a cell phone.
Suppose some of the entries are
Aman
Amazon
Neha Aman
and we type 'ama'
then the result should show all the above three enteries.
Also it should be possible to search using phone numbers.
Suppose you are a software vendor and you need to provide your API to a customer, but you don't want to give your source code. How would you do it?
Suppose you are a software vendor and you need to provide your API to a customer, but you don't want to give your source code. How would you do it?
We are planning an orienteering game.
The aim of this game is to arrive at the goal (G) from the start (S) with the shortest distance.
However, the players have to pass all the checkpoints (@) on the map.
Sample Input:
5 4
#####
#...#
#S#G#
#####
where 5 is the number of columns for the orientation map and 4 is the number of rows for the orientation map.
'S' is the starting point
'G' is the goal point
'@' is the checkpoint
'#' is the blocked point
'.' is the open point
Output:
9
you may pass through one point more than once.
an array is given.for each number at index i,find a number at index j such that aj 3.N number of books is given.each books is having some pages pi.How books should be alloted to m students so that maximum number of pages alloted to a student is minimum.Each student will read atleast one book.and one book can be read by only one person.find minimum value.
Consider the following class definition:
class Node {
List<Node> children;
void addChild (Node child);
}
Assume you have a node object like above. This node object can contain a child node object. Assuming you are given one of these objects, write a function to determine the maximum path length from the root node to the most distant remote node. .
Given an array[0, n-1], each number of the array is positive int. Your task is adding the operators,"+","*", "(",")" (add, multiply, parenthesis) to maximize the result . The position in the array is Fixed.
For example, "2,1,1,2", you can get (2+1)*(2+1)=9.
Follow up, if the number may be negative , how to solve it ?
There are 8 statues 0,1,2,3,4,5,6,7 . Each statue is pointing in one of the following four direction North, South, East or West.
John would like to arrange the statues so that they all point in same direction. However John is restricted to the following 8 moves which correspond to rotation each statue listed 90 degrees clockwise. (N to E, E to S, S to W, W to N)
Move A: 0,1
B: 0,1,2
C: 1,4,5,6
D: 2,5
E: 3,5
F: 3,7
G: 5,7
H: 6,7
Help John figure out fewest number of moves to help point all statues in one direction.
Input : A string initialpos consisting of 8 chars. Each char is either 'N,'S,'E,'W'
Output: An integer which represents fewest no. of moves needed to arrange statues in same direction. If no sequence possible then return -1.
Sample test cases:
input: SSSSSSSS
Output: 0
Explanation: All statues point in same direction. So it takes 0 moves
Test case 1:
Input : WWNNNNNN
Output: 1
Exp: John can use Move A which will make all statues point to North
Test Case 3:
input: NNSEWSWN
Output: 6
Exp: John uses Move A twice, B once, F twice, G once. This will result in all statues facing W.
Note: Read input from stdin and output from stdout
There is a file contains the digital number characters:
_ _ _
|_| |_ | |
|_| |_| |_|Each digital number contains 3x3 characters, read this file and output the int type number: 8 6 0
Here is the structure of a tree:
Node {
int value;
Node *parent;
}
All nodes are stored in a list right now
List {
Node n;
List *next;
}
print out each layer from left to right in a vertical position:
root layer1Child1 layer2Child1 layer4Child1
layer1Child2 layer2Child2
layer2Child3Write a function which, given two integers (a numerator and a denominator), prints the decimal representation of the rational number "numerator/denominator".
Since all rational numbers end with a repeating section, print the repeating section of digits inside parentheses; the decimal printout will be/must be
Example:
1 , 3 = 0.(3)
2 , 4 = 0.5(0)
22, 7 = 3.(142857)
etc..
Write a function which, given two integers (a numerator and a denominator), prints the decimal representation of the rational number "numerator/denominator".
Since all rational numbers end with a repeating section, print the repeating section of digits inside parentheses; the decimal printout will be/must be
Example:
1 , 3 = 0.(3)
2 , 4 = 0.(5)
22, 7 = 3.(142857)
etc..
Store a Tree of URI and give a java implementation for it to return handler for the URI , eg : url mapping like in spring-config.xml
Design a system that processes an infinite stream of data:
- each record comes as a tuple(url, html content)
- extract and store the occurences of:
urls, hosts, top-level-domains, in/out links of the page
We have one machine that has enough disk space but limited memory.
What data structures as building blocks would you use?
What are the testcases for a bottle opener? Can someone please give some hints?
To schedule a job which will run in weekdays between 3pm to 5pm , in a interval of 15min.
(its for oracle 10g so it doesn't support schedular
** without using repeat_interval.)
If there are 2 method in a testNG class one with @Test annotation and the other without @Test annotations, which method will run ?
Why you use ChromeDriver as the below. Why cant it work as Firefox driver by simply creating a reference
System.setProperty("webdriver.chrome.driver", "/path/to/chromedriver");
WebDriver driver = new ChromeDriver();
1. What works in the background when you write
Webdriver driver = new Firefox Driver();
Write a program to find distinct value out of an array. If you didnt find any duplicates return a empty array.
You are given a text file that has list of dependencies between (any) two projects in the soure code repository. Write an algorithm to determine the build order ie. which project needs to be build first, followed by which project..based on the dependencies.
Bonus point: If you can detect any circular dependencies and throw an exception if found.
EX: ProjectDependencies.txt
a -> b (means 'a' depends on 'b'..so 'b' needs to be built first and then 'a')
b -> c
b -> d
c -> d
Then the build order can be
d , c, b, a in that order
Given an array of positive integers that represents possible points a team could score in an individual play. Now there are two teams play against each other. Their final scores are S and S'. How would you compute the maximum number of times the team that leads could have changed?
For example, if S=10 and S'=6. The lead could have changed 4 times:
Team 1 scores 2, then Team 2 scores 3 (lead change);
Team 1 scores 2 (lead change), Team 2 score 0 (no lead change);
Team 1 scores 0, Team 2 scores 3 (lead change);
Team 1 scores 3, Team 2 scores 0 (lead change);
Team 1 scores 3, Team 2 scores 0 (no lead change).
Given a sorted array of 0’s and 1’s. Find out the no. of 0’s in it. Write recursive, iterative versions of the code.
Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
Given a set of restaurants (the number being quite large) and its geographical location(x,y) , you are allowed to do an significant amount of pre-processing on it. Now suppose there are x customers located at position (s,t), design an efficient algorithm to find the k nearest restaurants to these customers.
A ternary string consists of only a, b, c following the given 3 rules
1. a's cannot be consecutive.
2.b can appear only once.
Find the nuber of possible ternary string of length n.
Given a n-ary tree, Convert it into an array and return it. Construct the same n-ary tree from that array again.
how to do this round1 question 1:
http://www.geeksforgeeks.org/directi-interview-set-5-campus/
A string can contain only a, b or c. There cannot be 2 consecutive same character. First and last character cannot be same. Now given a string with ‘a’, ‘b’, ‘c’ or ‘?’. We need to find the string replacing ‘?’ that satisfy the above conditions. For multiple answer display lexicographically smallest string. For no answer possible display “Not Possible”.
There is a binary tree. We are given 3 nodes a, b and c. We need to find a node in the tree such that we remove all edge from that node we get a, b and c in three different trees
In a social network, online communities refer to the group of people with an interest towards the same topic.
People connect with each other in a social network. A connection between Person I and Person J is represented as C I J. When two persons belonging to different communities connect, the net effect is merger of both communities which I and J belonged to.
We are only interested in finding out the communities with the member count being an even number. Your task is to find out those communities
Given a mapping of alphabets to integers as follows:
1 = A
2 = B
3 = C
...
26 = Z
Given any combination of the mapping numbers as string, return the number of ways in which the input string can be split into sub-strings and represented as character strings. For e.g. given
"111" -> "AAA", "AK", "KA" -> 3
Valid combinations are ({1,1,1}, {1,11},{11,1}) = 3
"11" -> "AA", "K" -> 2
Valid combinations are ({1,1},{11}) = 2
"123" -> "ABC", "LC", "AW" -> 3
Valid combinations are ({1,2,3},{1,23},{12,3}) = 3
You don't have to return all the mappings, only the number of valid mappings.
Find the maximum depth of binary tree?
Once I wrote the code for this, interviewer asked me next question
in a Hadoop-like system, how do we manage multiple nodes collaborating together without having a master node?
my answer was running a back end job to randomly select a node to be a master node; and whenever the master node goes down, the backend job select a new node.
Given the following structure Record and we have million of records on disk.
struct Record
{
char[257] name;
int startTime;
char[257] description;
}
Now we want to keep a in-memory cache which is represented in class ManageRecords to perform 2 methods GetDesriptions and GetRecords. Given that we have very big memory and we can use any data structure so that the 2 methods can be performed really quick. Here are the questions:
1. what should be the return type for method GetDesriptions
2. what should be the return type for method GetRecords
3. what data structure should we use in the private part as commented out below
class ManageRecords
{
public:
ManageRecords();
? GetDesriptions(char[] name);
? GetRecords(int begin, int end); //do a range search based on startTime of structure Record
private:
// what data strcture should we use here?
}
while(scanf("%d,",&a))
{
//store a as you wish to
}Input given is : 1,2,3,4,5,6,7,8,9
while(scanf("(%d,%d),",&a,&b))
{
//store a and b as you wish to}
Input given is : (1,5),(8,11),(3,6),(10,20)
EXPLAIN INTERNAL WHOLE MECHANISM IN BOTH CASES
Hi, I was asked a this one at the interview. Below is the problem statement:
1) I have a array of n bitstring elements of width m bits, for example:
{1001, 0101, 1100, 0011, 1111, 0000, 0001}
2) We have to apply a filter such that out of these n elements, only k elements pass through the filter while the rest gets blocked, for example
{1001, 0101, 1100, 0011, 1111, 0000, 0001} -- filter -- > {1001, 1100, 1111}
3) Filter has been designed based on a concept of mask and ID.
mask: It tells which bits to consider out of the m bit bitstring elements. Only those bits which are set to '1' would be used for checking while the rest be ignored. for example, a mask of {1000} would mean only 4th bit would be considered for checking while the filter won't care about the other bits of an element.
ID: It is the allowed value for the designed mask. for example, an ID of 1xxx (where x is don't care) with a mask of 1000 means that any element which has 4th bit as '1' would be allowed while if the 4th bit is '0', that element would be blocked. Since the mask doesn't check the 1st, 2nd and 3rd bit, any value, '1' or '0' would be allowed to be passed through the filter
For the above example, a single mask of 1000 and ID of 1xxx solves the problem. We need to find a generic solution for any set of n elements and k allowed elements. All of the k element might not get covered by a single mask and ID. We need to find the optimum solution using minimum number of mask,ID sets with their values.
[Phone screen]
Let's say I gave you a long String and I wanted you to tell me the most common word in that String. How would you do that?
follow-up: OK, how would you estimate the size and time complexity of this solution? How would you estimate the ACTUAL size usage? (Hint: how many words are in the English language? Would having a dictionary in front of you help?)
follow-up #2: OK, how about if I gave you the entire works of Alexandre Dumas, one of the most prolific authors in history. How would your solution work? How could you change it to solve this more specific problem?
follow-up #3: Now, what if we wanted to find the most common PHRASE in his writings. (Upon clarification, the interviewer wouldn't give a specific length, so I clarified to finding as long as a common 10 word phrase, because anything longer is unlikely.)
[Phone screen]
Tell me about the Java Collections framework, what are its main interfaces. OK, what are the main differences between the Set and List interfaces? What do you give up if you go from a List to a Set, and what do you get in exchange for this if you go from a List to a Set? How would you go about guessing the order of an iteration() of HashSet if I told you I was going to insert the strings "first", "second", "third", "forth", and "fifth"?
Let's say I gave you a long String and I wanted you to tell me the most common word in that String. How would you do that?
follow-up: OK, how would you estimate the size and time complexity of this solution? How would you estimate the ACTUAL size usage? (Hint: how many words are in the English language? Would having a dictionary in front of you help?)
follow-up #2: OK, how about if I gave you the entire works of Alexandre Dumas, one of the most prolific authors in history. How would your solution work? How could you change it to solve this more specific problem?
follow-up #3: Now, what if we wanted to find the most common PHRASE in his writings. (Upon clarification, the interviewer wouldn't give a specific length, so I clarified to finding as long as a common 10 word phrase, because anything longer is unlikely.)
Tell me about the Java Collections framework, what are its main interfaces. OK, what are the main differences between the Set and List interfaces? What do you give up if you go from a List to a Set, and what do you get in exchange for this if you go from a List to a Set? How would you go about guessing the order of an iteration() of HashSet if I told you I was going to insert the strings "first", "second", "third", "forth", and "fifth"?
[Phone screen]
Tell me what you know about the java.lang.Object class. OK, what are best practices for the equals method? How would you implement an equals method for a class with 100s of data fields?
If you run the same program twice, what section would be shared in the memory?
Follow up, is the text portion of memory share? Why not?
What do you do if your program does a core dump?
(Analyze code dump)
Name all the possible ways a program would do core dump.
Write a function that accepts an n-dimension array and prints its values--For array of any dimension.
What is the layout of multi-dimensional array in the memory?
Given a number n, write a function that writes a Fibonacci sequence to number n.
It was part of a bigger question --a large piece of code.
Implement << operator. What are the differences of implementation as a member function and a non-member function
What does an iterator in C++ point to in case of a vector vs. list. Where would it point to if the prior links are deleted in the list? In case of a vector if it points to a specific index, where would it point to if the prior indexes are deleted?
What C++ data structures would you use to implement LRU cache? Show implementation.
How would you implement this:
object["String for a security name"]["another string"] = another_objectWhat are the various ways of doing IPC in Unix/Linux? How do you implement it?
Write a Program to find out Whether a given String can be a Palindrome i.e. we need to see for the palindrome after rearranging the words in that string.
example: lets say we have a string "aabbccd" so it can be a palindrome after rearranging the words "abcdcba".
For this I need to find out the optimal solution.
Write a Program to find out that a given String can be a Palindrome.we need to see for the palindrome after rearranging the words in that string.
example: lets say we have a string "aabbccd" so it can be a palindrome after rearranging the words "abcdcba".
For this I need to find out the optimal solution.
Any feedback about my performance would be helpful.
I have my (unfinished) answer that I managed to code by the end of the interview. I also have my answer that I coded after the interview was over. Did I miss anything, or is there a simpler answer out there? I feel like I was pretty close, although I didn't finish, which feels pretty bad.
Palindrome question:
Is a string reversible?
Ignore illegal characters; ignore case. Only alphabetic characters are valid.
Here was my answer after ~45 mins:
/*
* Compare both ends for equality, meeting in the middle
*/
public static boolean isReversible(String s) {
char[] chars = s.toCharArray();
int back = chars.length - 1;
int front = 0;
int middle = chars.length / 2;
while (front < back) {
char backChar = chars[back];
char frontChar = chars[front];
// check backChar as a alpha char
while (backChar < ‘a’ || backChar > ‘z’) {
back--;
if (back < middle)
return false;
// Double check for multiple non-alpha chars
middle--;
backChar = chars[back];
}
// check frontChar as a alpha char
while (frontChar < ‘a’ || backChar > ‘z’) {
front++;
if (front >= middle)
return false;
// Double check for multiple non-alphas
middle++;
frontChar = chars[front];
}
// We know that frontChar and backChar are both alpha
// Check whether front and back are not past the middle
if (frontChar != backChar)
return false;
front++;
back--;
}
return true;
}Here was an answer that I came up with after the interview, which I believe is complete after manual testing:
/*
* Compare both ends for equality, meeting in the middle
*/
public static boolean isReversible(String s) {
s = s.toLowerCase();
char[] chars = s.toCharArray();
int back = chars.length - 1;
int front = 0;
while (front < back) {
char backChar = chars[back];
char frontChar = chars[front];
// check backChar as an alpha char
while (backChar < 'a' || backChar > 'z') {
back--;
if (back < front)
return true;
backChar = chars[back];
}
// check frontChar as an alpha char
while (frontChar < 'a' || frontChar > 'z') {
front++;
if (front > back)
return true;
frontChar = chars[front];
}
if (frontChar != backChar)
return false;
front++;
back--;
}
return true;
}I have two number A = 100 and B = 145;
I want to find all number that have digit of number is increase
Thanks
Given a 20 GB file and 2GB RAM, how to parse it and detect where to break it, concepts of memory management.
Write a calculator program in a Java that evaluates expressions in a very simple integer expression language. The program takes an input on the command line, computes the result, and prints it to the console. For example:
% java calculator.Main “mult(2, 2)”
4
Few more examples:
Input
Output
add(1, 2)
3
add(1, mult(2, 3))
7
mult(add(2, 2), div(9, 3))
12
let(a, 5, add(a, a))
10
let(foo, 5, let(bar, mult(foo, 10), add(bar, foo)))
55
let(a, let(b, 10, add(b, b)), let(b, 20, add(a, b)))
40
An expression consists of:
· Numbers: integers between Integer.MIN_VALUE and Integer.MAX_VALUE
· Variables: strings of characters, where each character is one of a-z, A-Z
· Arithmetic functions: add, sub, mult, div, each taking two arbitrary expressions as arguments. In other words, each argument may be any of the expressions on this list.
· A “let” operator for assigning values to variables:
let(<variable name>, <value>, <expression where variable is used>)
As with arithmetic functions, the expression where the variable is used may be an arbitrary expression from this list.How to remove file named "~" ?
Given a file containing a list of ip addresses that have lost their dots(.'s), write a program to find the ip addresses, assume ipv4. input: 11111 output. 1.1.1.11, 11.1.1.1, etc
Giiiven a matrix of -1's and 0's, display a matrix which contains minimum distance to reach nearest 0 for that particular position.
Example:
Input: -1 0 -1
-1 -1 -1
-1 -1 -1
Ouutput:
1 0 1
2 1 2
3 2 3
Write a shell script to reverse a string without using inbuilt function.
Given a binary tree, change the value in each node to sum of all the values in the nodes on the left side of the node.
Eg 1
/ \
2 3
3
/ \
2 6
solved this question using int* he asked me to do it without integer pointer.
Given an array of positive negative no, u need to find max sum we can achieve using this array, condition is u cannot use two adjacent items.
Print sum in one line
Print all items that contribute this sum in other line using space separated char
if all items r negative then print least negative no
-1 4 5 -2 -6 6
output-
11
5 6
we want it inplace and linear time.
Focus on printing items that contribute max sum.
the address of a[5][5] is 1000,wat is the address of a[7][9]
Write a program to find the distinct elements out of an array but not using loop, using XOR
Design a data structure which has following operations:
1. void add(e)
2. void delete(e)
3. boolean contains(e)
4. e getRandom()
5. e getMostRecent()
All operations should be preferably O(1)Write a program to find prime number and let me know the 2^n complexity of your program
write a program to find the distinct values from an array but not using loop , only by using XOR
Write a program to find the the prime numbers and let me know the 2^n complexity algorithm
Kindly find the question below:
Design a data structure which has following operations:
1. void add(e)
2. void delete(e)
3. boolean contains(e)
4. e getRandom()
5. e getMostRecent()
All operations should be preferably O(1)
Write a program to remove the duplicate elements from an array. Dont use loop logic use XOR function to write a solution.
there is PCB robot move from point of beginning go to destination find the shortest distance/shortest path from starting to destination
There are at most eight servers in a data center. Each server has got a capacity/memory limit. There can be at most 8 tasks that need to be scheduled on those servers. Each task requires certain capacity/memory to run, and each server can handle multiple tasks as long as the capacity limit is not hit. Write a program to see if all of the given tasks can be scheduled or not on the servers?
Ex:
Servers capacity limits: 8, 16, 8, 32
Tasks capacity needs: 18, 4, 8, 4, 6, 6, 8, 8
For this example, the program should say 'true'.
Ex2:
Server capacity limits: 1, 3
Task capacity needs: 4
For this example, program should return false.
Got some idea that this needs to be solved using dynamic programming concept, but could not figure out exact solution.
Wap to insert space in a string in all possible way and print.
E.g- string is abcd
output a_bcd,a_b_cd,a_b_c_d
ab_cd,ab_c_d,
abc_d
You are given an array, that is sorted, however was rotated to the right by a certain distance. The array may contain duplicated values. Find the index of a given element in the array.
Example: {3, 9, 9, 9, 8, 10, 12, 13, 1, 2, 3}, element = 3, returns, any of indexes that 3 is present.
Given an array containing only stars '*' and hashes '#' . Find longest contiguous sub array that will contain equal no. of stars '*' and hashes '#'.
Order (n) solution required
Given an array containing only stars '*' and hashes '#' . Find longest contiguous sub array that will contain equal no. of stars '*' and hashes '#'.
An array contain 6 different numbers, only 1 number is repeated for 5 times. So now total 10 numbers in array, Find that duplicate number in 2 steps only?
Given a 2 dimensional matrix where some of the elements are filled with 1 and rest of the elements
are filled. Here X means you cannot traverse to that particular points. From a cell you can either traverse to left, right, up or down
Given two points in the matrix find the shortest path
between these points
For example if the matrix is
1 1 1 1 1
S 1 X 1 1
1 1 1 1 1
X 1 1 E 1
1 1 1 1 X
Here S is the starting point and E is the Ending point
Design a system like friend's functionality in facebook. should have all features of facebook's friends functionality. like for each person , he can have any number of friends , he will get suggestions for new firends , showing common friends if we visits any other profile . algo should be scalable , robust .
Problem Statement
You have two strings A and B. Each one contains some letters and exactly one asterisk.
You have to replace the asterisk in each string with a letter sequence (possibly of zero length) so that the resulting two
strings are equal. This equal string is what you have to return. Attempt to return the shortest possible string.
The letter sequences may be same or different.
If it is not possible to make the given strings equal, return the string "not-possible".
Additional Constraints
- A and B will contain only uppercase letters and asterisks.
- A and B will contain one asterisk each.
Examples
0)
"SOCIA*TWIST"
"SOCIALTWI*T"
Returns: "SOCIALTWIST"
1)
"HELLO*"
"HI*"
Returns: "not-possible"
2)
"PROFESS*"
"*PROFESS"
Returns: "PROFESS"
3)
"*EXAMPLETEST"
"THIRDEXAMPLE*"
Returns: "THIRDEXAMPLETEST"
4)
"*TELL"
"*AFRIEND"
Returns: "not-possible"
5)
"*"
"B*"
Returns: "B"
6)
"*C"
"D*"
Returns: "DC"
program should be written in java
Find the longest words in a given list of words that can be constructed from a given list of letters.
Your solution should take as its first argument the name of a plain text file that contains one word per line.
The remaining arguments define the list of legal letters. A letter may not appear in any single word more times than it appears in the list of letters (e.g., the input letters ‘a a b c k’ can make ‘back’ and ‘cab’ but not ‘abba’).
Here's an example of how it should work:
prompt> word-maker WORD.LST w g d a s x z c y t e i o b
['azotised', 'bawdiest', 'dystocia', 'geotaxis', 'iceboats', 'oxidates', 'oxyacids', 'sweatbox', 'tideways']
Tip: Just return the longest words which match, not all.
Question 1.3 from Crack the Coding Interview (Design an algorithm and write code to remove the duplicate characters in a string
without using any additional buffer NOTE: One or two additional variables are fine)
Is just me or both solutions are wrong? I've tested with {'a', 'b', 'c', 'c', 'd', 'a'} and it finish with bcdda
You are given a mxn grid arr[][] and you stand at cell arr[p][q]. In 1 'move' you can either go up, down , left or right. Tell the probability that after taking 'k' moves, you are still inside the grid.
CODE:
(Can you point out any mistake)
#include <stdio.h>
#include <stdlib.h>
void traverse(int m, int n,int cur_x,int cur_y,int moves,int * in,int * tot)
{
if(moves==0)
*tot = *tot+1;
if(moves==0 && !(cur_x>=m||cur_y>=n||cur_x<0||cur_y<0))
*in = *in +1;
traverse(m,n,cur_x,cur_y+1,moves-1,in,tot);
traverse(m,n,cur_x+1,cur_y,moves-1,in,tot);
traverse(m,n,cur_x,cur_y-1,moves-1,in,tot);
traverse(m,n,cur_x-1,cur_y,moves-1,in,tot);
}
int main()
{
int m = 5, n = 5;
int in=0,tot=0;
int k,p,q;
scanf("%d%d%d",&k,&p,&q);
traverse(m,n,p,q,k,&in,&tot);
printf("%d/%d ",in,tot);
return 0;
}Write a function to label connected components (using 4-connected neighbors) in a binary image.
You may use any language or data structures, but you may not use any existing APIs/libraries to find the components.
Example:
Input image
0 0 0 0 0 1 1 0 0 0
1 1 0 0 1 1 0 0 0 0
1 1 1 0 0 1 1 0 0 0
0 0 0 1 1 0 0 0 0 0
Output Image
0 0 0 0 0 1 1 0 0 0
2 2 0 0 1 1 0 0 0 0
2 2 2 0 0 1 1 0 0 0
0 0 0 3 3 0 0 0 0 0
What is the following program trying to do?
#define SIZE (1<<31) // 2 Gb
int main()
{
char *p=malloc(SIZE);
memset(p, 0, SIZE);
}a. Trying to crash OS by allocating lot of memory
b. Trying to calculate amount of system memory
c. Trying to allocate virtual memory and makesure memory is in physical memory
d. It is a useless program because the system will not satisfy memory request
Implement printf() library function using system-calls assuming a single argument which is a string
eg: printf("Hello world\n");
void printf(char *str)Implement sleep() in kernel mode using C-pseudo code
void sleep(int seconds) {}Implement a trivial spinlock and spinunlock functions using C-pseudo code eg: spinlock(&lock);
void spinlock(int *lock){}void spinunlock(int *lock){}Which one of the following applies to multi-core system?
a. Multiple users can use the system at the same time
b. The kernel can run in SMP mode
c. Multiple tasks can execute in parallel without the need for scheduling
d. semaphores and mutexes should be replaced with spinlock
The user space program running in foreground mode is hung. How will you debug the hang without exiting or killing the program?
What are the differences between interrupt and exception?
Explain how page fault and segmentation fault is handled/resolved
design a durable API
web-based chatroom application
given 50K static online web pages, how do I identify all of them that have a phone numbers (assme 10 dights in a row)
Given a multidimensional array like below:
0 1 0 0 3
0 3 3 0 0
0 0 0 0 2
0 0 1 0 2
0 0 0 0 0"objects" are considered groups of numbers that touch along top, left, right, or bottom edges.
Find the number of objects.
For example given the above array, your code should detect 4 unique "Objects". {1,3,3}, {3}, {1}, and {2, 2}.
To design classes and methods for casino cards games, what would you consider when doing it?
Write a method that takes a binary tree and return whether the tree is sorted.
Define the following classes
- Book which has the fields title(String), author (String), count (int). Also define the following function in the class
increment() : increases count by 1.
decrement() : reduces the count by 1. If count is 0, it remains 0.
- Library which has a field books (of type Book[]). It also has the following functions
getCount(String title) : given the title of a book as parameter, return how many copies of the book are there in the library
getCount(Book book) : given the object of type Book as parameter, return how many copies are there of that book in the library
getCount() : returns the total number of books in the library
getDiffCount() : returns the number of different books in the library
addBook(Book book) : given an object of type Book as input, increment its count if it is in the library else adds the book.
removeBook(Book book) : given an object of type Book as input, decreases the count of that book if it exists in the library. If the count becomes 0, it is removed.
Define a class Passenger having the fields name (String), age (int), gender (char : M/F), weight (int). Define 2 constructors for this class, one with parameters and one which has no parameters.
Also define a class Train in which there are the following functions. Note that there are no fields in the class Train.
- int getTotalWeight(Passenger[] passengers) - returns the total weight of all the passengers in the input
- int countChildren(Passenger[] passengers) - returns the number of children in the input passengers. A child is defined as age 12 or below
- int countGender(Passenger[] passengers, boolean male) - returns the number of males if true else returns the number of females. A male has the gender 'M' and a female 'F'
- Passenger[] addPassenger(Passenger[] passengers, Passenger passenger1) - returns a Passenger[] which contains all the passengers and also passenger1.
You are given an array of both negative and positive integers. You need to rearrange the array such that positive and negative numbers alternate. Also, the order should be same as previous array and only O(1) auxiliary space can be used and time complexity boundation O(n).
eg. -2 3 4 5 -1 -6 7 9 1
result – 3 -2 4 -1 5 -6 7 9 1.
In a programming language,we have a conditional statement like "a ? b : c",(you can assume all the expressions here could be represented by single character).The task is to generate a syntax tree like this.
a
b c
Here are more examples of the input and output,
a ? (b ? c : d) : e
a
b e
c d
a ? b : (c ? d :e)
a
b c
d e
You have been given a 2D array of char and a String as input. Return a string consisting of the chars in the input string which are not present in the 2D array.
Given a binary tree where all the right nodes are leaf nodes, flip it upside down and turn it into a tree with left leaf nodes.
Keep in mind: ALL RIGHT NODES IN ORIGINAL TREE ARE LEAF NODE.
/* for example, turn these:
*
* 1 1
* / \ / \
* 2 3 2 3
* / \
* 4 5
* / \
* 6 7
*
* into these:
*
* 1 1
* / /
* 2---3 2---3
* /
* 4---5
* /
* 6---7
*
* where 6 is the new root node for the left tree, and 2 for the right tree.
* oriented correctly:
*
* 6 2
* / \ / \
* 7 4 3 1
* / \
* 5 2
* / \
* 3 1
*/Print a tree in Level Order with a newline after each depth
/**
* Sample input:
*
* 1
* / \
* 3 5
* / \ \
* 2 4 7
* / \
* 9 8
*
* Expected output:
* 1
* 3 5
* 2 4 7
* 9 8
* ==========
*/How to split a string using spaces with a given condition, the string inside quotes (") will not be split.
we have website having several web-pages. And also there are lot many user who are accessing the web-site.
say user 1 has access pattern : x->y->z->a->b->c->d->e->f
user 2 has access pattern : z->a->b->c->d
user 3 has access pattern : y->z->a->b->c->d
user 4 has access pattern : a->b->c->d
and list goes on for lot many users which are finite and numbered.
Now the question is we have to determine the top 3 most occurring k-Page-sequence.
for the above example result will be : (k=3) a->b->c , b->c->d , z->a->b.
Given a string array and a pattern, find the number of occurrences
i.e. given
int[] a = new int[]{12, 789, 567, 1, 2};Find out how many times a pattern like 12789 occurs. You can do "12" and "789" one time and also "1" "2" and "789" to make the pattern as well.
Estimate the number of USPS boxes (i.e. ones at home address and NOT P.O. Boxes) in the U.S. You are not given USPS data, of course.
Q2 : You have been given an array of int as input. Return the number of times the digit 1 appears in the array.
count1s({2,11,5,199,4,7}) = 3 (twice in 11 and once in 199)
count1s({234,-11,-105,23841,101010,705}) = 7 (twice in -11, once in -105, once in 23841 and thrice in 101010)
K largest elements from a big file or array.
If we're given a project budget and limit of completion that is 6 months, then which approach is good, requirements capture, req analysis through modelling, detailed analysis or feasibility analysis?
Write a code to test whether string s2 is obtained by rotating the string s1 by 2 places.
e.g S1="amazon" S2="azonam" return true
S1="quality" S2="lityqua" return false
Write a code to find duplicate elements in array and total count of duplicate elements.
eg. arr={5,3,4,6,7,5,3,2,1}
Duplicate elements:- 5,3
Total duplicate count:- 2
Write the test data for the function which takes input value as floating number and precision. It returns the output by rounding the value nearest to precision value.
e.g roundOff(3.4567,2) output will be 3.55
How will you debug the issue when trying to sync the contacts of smartphone with PC and all the contacts does not sync.
Write the test scenarios and test cases for PC based phot o preview software when the camera is connected to PC using USB.
Find first index of string s2 , If any anagram of a string s1 is exist in another string s2 ?
e.g. s1 abcd
s2 abcdefcdbacd
output should be 0 ,5, 6,7 .
Design software system for a multiplex assuming database server is available - List requirements, DB tables design, APIs. Follow up question how to integrate with third party ticketing systems? how to pass seats availability to ticketing systems?
Given an array of heights of poles. Find the no of poles which are visible if you are standing at the ith pole
Given 2 set of arrays of size N(sorted +ve integers ) find the median of the resultant array of size 2N.
(dont even think of sorting the two arrays in a third array , though u can sort them. Try something better than order NLogN
A game is being played with the following rules :
- The first player says 1, the next 2 and so on.
- If a number is a multiple of 4 or 7 then that number is skipped and the next number is spoken. However if the number is a multiple of both 4 and 7 then the number is not skipped.
Define a function which taken a number n as input and returns the nth number which will be spoken.
nthNumber(10) = 15 (the order of numbers spoken is 1,2,3,5,6,9,10,11,13,15)
Why is returning pointer to a node in linked list from a pointer is unsafe and sometimes gives wrong answers.
Given an array of strings as input, return an array of all strings that have repeated chars that appear together. For e.g. in "hello" l and in "summer" s is a repeated char that appears together. However in "robot" o is not a repeated char as it does not appear together.
repeatChars({"hello","robot","summer","elephant"}) = {"hello","summer"}
1 represent A, 2 rep B etc and 26 rep Z. Given a number, find number of possible decoding for this number. No need to consider number starts with zero. Eg: input – 1234, output – 3(ABCD, AWD, LCD)
Most efficient way to check whether a number is Prime or not.
struct node
{
int data;
struct node* left;
struct node* right;
};
void Postorder(struct node* root,struct node** leaf)
{
if (root == NULL)
return;
if(root->data%2==0)
*leaf->left=root; //WHY I'M GETTING PROBLEM IN THIS LINE
//[Error] request for member 'left' in '* leaf', which is of non-class type 'node*'
Postorder(root->left,leaf);
Postorder(root->right,leaf);
}
int main()
{
struct node *root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
struct node* leaf=root;
Postorder(root,&leaf);
getchar();
return 0;}
Write a method to return first five 10 digit prime numbers
Write a method to return first five 10 digit prime numbers.
Design a phone book such that fields are searchable with name , with number. Later enhanced teh question asking searchable with address as well.
Given 13 cards only of one suite say spade. You have to write algorithm to arrange the cards in stack such that you put cards in sequencial order at bottom & remove top you should get cards in sequencial order.
forex:- put first top card at bottom now remove the topmost should be one of spade.
-put top two cards one by one at the bottom, now remove the topmost should be two of spade.
- similarly do three time.. four time .... and so on till king.
Jack=11, queen=12, king=13
time complexity should be nlogn
Ans should be like this:
4, 1, K, J, 2, 10, 6, 7, 3, 5, Q, 9, 8
From this sequence put top one card at bottom & now top card should be number 1. as below
1, K, J, 2, 10, 6, 7, 3, 5, Q, 9, 8, 4 - top one card placed at bottom
K, J, 2, 10, 6, 7, 3, 5, Q, 9, 8, 4- top card is 1 which is removed
Now do same with two cards as below
2, 10, 6, 7, 3, 5, Q, 9, 8, 4, K, J- top two placed at bottom.
Now topmost is 2nd number so remove it
10, 6, 7, 3, 5, Q, 9, 8, 4, K, J
do same for 3, 4 ... till K
3, 5, Q, 9, 8, 4, K, J, 10, 6, 7
5, Q, 9, 8, 4, K, J, 10, 6, 7
.
.
The card we remove should be in 1 to k sequence i.e. 1,2,3,4,5,6,7,8,9,10,J,Q,K
But here we need to find how to form the sequence in NlogN i.e.
Ans should be like this:
4, 1, K, J, 2, 10, 6, 7, 3, 5, Q, 9, 8
There are three files
original.txt,encryption.txt and decryption.txt
original file contains "ABCEZYAR"
it should be encrypt like "12352625118"
and when we decrypt code then original massage should be return "ABCEZYAR".
An analyst at Amazon is conducting a satisfaction survey, sampling from a list of 10,000 new users. The list includes 2,500 French users, 2,500 German users, 2,500 Italian users, and 2,500 Portuguese users, The analyst selects a sample of 400 users, by randomly sampling 100 users of each country. Is this an example of simple random sample?
I applied online through Amazon page, and they contacted me right immediately like on that day which was scary for me. I guess they embody truly the culture of moving fast. I got an e-mail with to complete some online test with 13 questions and they were on:
13 questions:
9 Analytical Multiple Choice Questions – focusing on sets, trend analysis, calculus, stats, etc.
1 open ended basic SQL question.
1 open ended normalization question.
1 Multiple Choice English language comprehension question.
1 open ended language question (this part should be 200 – 300 words).
The entire online assessment test was conducted through hackerrank.com and it was for 90 min.
Personally I did not go and complete the Quiz within couple of day. I did take my time to prepare and I was right. It is a difficult test. I did use apps like ‘the impossible interview’ and ‘the aptitude interview’ from iTunes app store to prepare. They were a help.
Given an array of integers. We have to find the max element of the array, which is at multiple places in the array and return any one of the indices randomly.
Which is faster?
while(1) {}
or
while(2) {}
I said both have same speed as the expression inside while should finally evaluate to true or false. in this case both evaluates to true and there are no extra instructions inside the while so both have same speed of execution. Interviewer said while (1) is faster than while (2).
I do not agree . do you ?
By the way interviewer was a senior manager (i,e. does not code on day-to-day basis)
Given data of set of persons {data contains his name , number , address} , and also , each person has 4 ranks. One is global rank , one is region rank , one is centre rank and one is family rank. each rank is independent of other. Design algorithm n ds , to accomodate this requirement. operations that can be done are , change of ranks , insert new person , . searching on rank wise {can be any rank}.
suggestions on this please.
An input file called input.txt consists of data in the following format:
22 Data Structures 45
23 Maths 2 52
23 Maths 3 57
22 English 51
26 Data Structures 72
23 Data Structures 63
26 English 81
Each line consists of three fields "Student ID," "Subject," and "Marks." "Student ID" and "Marks" are integers and "Subject" is a string that does not contain '|' or newlines (but might contain digits). There can be any number of students and up to 6 subjects. You have to read this file, and print the average marks in "Data Structures," across all students.
Thus for the above file, the output would be:
60
Kindly let me know the soln in C#.
Context:
There's a network of computers. Each computer accepts connections at certain incoming port numbers and can make outgoing connections to a possibly different set of outgoing port numbers. Some computers are connected through cables to each other. Computer A can directly transmit data to computer B if and only if:
there is a direct cable connection between computer A and B,
there exists a port number X, that is an outgoing port on computer A and an incoming port on computer B.
Some of the computers are connected directly to the outside, unsafe network. If there is a way to connect to computer Z either directly or indirecly from the outside network, that computer Z is "at risk". If there is no way to connect to computer Z from outside network, that computer is "safe".
Question:
Write a program that given:
computers (each computer has incoming and outgoing port numbers),
cable connections between computers (a pair of computers),
computers accessible from outside network,
Print out all "safe” computers and all possible ways to access a specific computer from outside network.
Write test cases for testing browser extension (chrome in particular)
What tests would you write for testing chrome browser extension?
Come up with an algorithm for mapping the following scenario:
You have a source LED which has the following possible output combinations.
1. OFF
2. ON- Having RED SOLID color
3. ON- Having a GREEN BLINKING (one flash every second)-> This will result in LED turning OFF->ON and then OFF->ON
every one second.
When the source LED changes it's state (ON->OFF, OFF->ON, or changes COLOR ), you will get an interrupt.
As part of the interrupt handling, you will have to drive a single LED which has these possible values:
OFF-> when the source LED is OFF
RED-> when the source LED is RED SOLID
GREEN->when the source LED is green flashing.
Give the algorithm of only mapping these scenario and not the interrupt handling.
What happens when we pass negative indices to an array? Would the compiler allow it?
print all the binary values of number from 1 to n , each number’s binary should be printed in 0(1).
for eg: n = 6
then print 1 10 11 100 101 110. printing 1, 10 ,11 ,100,101,110 should be in o(1) each
Given the integers from 1 to n, determine how many valid binary heaps can be constructed with these numbers.
Implement an algorithm to print all valid (e.g., properly opened and closed) combinations of n-pairs of parentheses.
EXAMPLE:
input: 3 (e.g., 3 pairs of parentheses)
output: ()()(), ()(()), (())(), ((()))
This question is from "Cracking the coding interview" (Fourth Edition) and I think that I found mistake in the answer.
Given a string and a number k, break the string up into tokens and return the k most frequently occurring tokens. The algorithm should take O(n) time, where n is the length of the string.
hii frnds, i have one doubt..
why we need to use "sealed" even we have "private" to prevent inheritance(we cant inherit private members)
Given two files which contain very large size of number, say the size of the file is 5 GB.
That means that you can not load the whole file into memory. How would you add these two files and store the result in another file? How would you optimize algorithm?
Output top N positive integer in string comparison order. For example, let's say N=1000, then you need to output in string comparison order as below:
1, 10, 100, 1000, 101, 102, ... 109, 11, 110, ...
Find the longest sequence of prefix shared by all the words in a string.
"abcdef abcdxxx abcdabcdef abcyy" => "abc"
Given a function
getRandomTripplet()
which returns a random triplet of letters from a string. You don't know the string using calls to this function you have to correctly guess the string. the length of the string is also given.
Lets say the string is helloworld the function getRandomTriplet will return things like
hlo
hew
wld
owo
the function maintains the relative order of the letters. so it will never return
ohl since h is before o in the string.
owe since w is after e
The string is not known you are only given length of the string.
Give a function
getRandomTripplet()
which returns a random triplet of letters from a string. You don't know the string using calls to this function you have to correctly guess the string. the length of the string is also given.
Lets say the string is helloworld the function getRandomTriplet will return things like
hlo
hew
wld
owo
the function maintains the relative order of the letters. so it will never return
ohl since h is before o in the string.
owe since w is after e
The string is not known you are only given length of the string.
given a binary tree, assign a new next pointer to each node, such that next pointer points to any node which is right side of the node(ie it may point to its sibling right node , or a left node of next subtree).
if no node on right or if the node itself if right most, the next points to null
6/ \7-------->2/ \ / \1 - ->5-->4 ->13Given a NxN matrix which contains all distinct 1 to n^2 numbers, write code to print sequence of increasing adjacent sequential numbers.
ex:
1 5 9
2 3 8
4 6 7
should print
6 7 8 9
Suppose u have a buffer of size 1024 byte, and there are m writer thread that will write on this buffer, if a writer get a chance to write on buffer it will completely fill it. If buffer is already written then no other writer thread should be able to write data on it till buffer is not processed by readers threads. There are n reader threads.
if buffer is full then one of reader thread should able to read it and make empty then again one of writer thread fill buffer.
buffer completely filled in single shot it mean if writing started it be completed fully.
Write a solution so all writer thread get equal chance to write on buffer and same way all readers threads get equal chance to read data from buffer.
Ex- if 3 writer and 3 reader
after 3 time write operation every thread done 1 time write operation and same way each reader also 1 time processed data.
Any more info u need ask me....
Given is a matrix arr[n][n], find a submatrix sub[m][m] such summation of all the elements in submatrix is maximum.
Given condition,
1. m <= n
2. m >= 2
3. consider positive, negavive and zero integers in arr[n][n]
4. User provide n.
What is difference between critical section and mutex.??
Can we use mutex across the process??
float range is only 4 byte but if apply the more than 4 byte also execute why?
all the problem are easy solve using printf &scanf
but my question is what is the necessity of using other input&output function
if apply same input for float and double .some time the vale is display &some time display not same .why this kind of output display..how to rectify the problem
Traverse a given 2D matrix from given source to destination in such way that every cell should be visited exactly one time (we have to cover all cells of matrix exactly once and have to reach at destination).
Given N sets of integers, remove some sets so that the remaining all sets are disjoint with one another. Find the optimal solution so that the number of sets remaining at the end is maximum
Power set P(S) of a set S is the set of all subsets of S. For example S = {a, b, c} then P(s) = {{}, {a}, {b}, {c}, {a,b}, {a, c}, {b, c}, {a, b, c}}.
If S has n elements in it then P(s) will have 2^n elements
public List<List<int>> ComputePowerSet(int[] nums)
{
List<List<int>> powerSet = new List<List<int>>();
if (nums == null)
return powerSet;
bool[] bits = new bool[nums.Length];
bool overFlowBit = false;
while (!overFlowBit)
{
List<int> lst = new List<int>();
for (int i = 0; i < nums.Length; i++)
{
if (bits[i])
lst.Add(nums[i]);
}
//function PlusOne returns false if the end is reached i.e. 2^n
if (!PlusOne(bits))
overFlowBit = true;
powerSet.Add(lst);
}
return powerSet;
}
public bool PlusOne(bool[] bits)
{
bool carry = true;
//add i i.e. true to the bits
int i = bits.Length-1;
while (i >= 0 && carry)
{
bool b = bits[i];
bits[i] = b ^ carry;
carry = b & carry;
i--;
}
//if carry is true implies reached the end i.e. 1111 + 1 = 0000, carry = 1
return !carry;
}Find the deepest node in a binary tree:
Example:
A
/ \
B C
/ \ / \
D E F G
\
H
Return Node ‘H’
Find the deepest node in a binary tree:
Example:
A
/ \
B C
/ \ / \
D E F G
\
H
Return Node ‘H’
Write a function to remove the duplicated characters from a string, and maintain the order of the characters.
ex. “abracadabra” ? “abrcd”
Lets suppose we are given two paragraphs . Now our task is to find the matching percentage between two paragraphs . So please tell me a efficient algorithm to do same ?
given n*1 rectangle so n square of 1*1 dimension, find in how many ways can we color the squares with red, green and blue color such that red color should be used at least n times, green color g times and blue color b times.
Design Tic-tac-toe game?
Mention all the classes, object that will be used in Java.
what is the difference between internal repository and internet repository?
How to find median of a stream of integers....
interviewer was not interested using insertion sort....
Any better way to do this??
what about your project performance...how can i answer this question?
How to convert http to https in java....can anyone knows please tell me?
Give efficient implementation of the following problem.
An item consist of different keys say k1, k2, k3. User can insert any number of items in database, search for item using any key, delete it using any key and iterate through all the items in sorted order using any key. Give the most efficient way such that it supports insertion, search based on a key, iteration and deletion.
Write a pattern matching function using wild char
? Matches any char exactly one instance
* Matches one or more instances of previous char
Ex text = "abcd" pattern = "ab?d" True
Ex text = "abccdddef" pattern = "ab?*f" True
Ex text = "abccd" pattern = "ab?*ccd" false
if u need more sample input ask me
Programme 1
class A
{
private:
A()
{
}
};
int main()
{
//Do not create an object of A
}
Is there any error
Compile Time error Y/N
Run Time error Y/N
Programme 2
class A
{
private:
A()
{
}
};
class B : public A
{
};
int main()
{
//Do not create an object of A or B
}
Is there any error
Compile time Y/N
Run Time Y/NHow to design a multi key hash map ( key count can be dynamic. if there are two keys , initiallly which can be used to find the value , keys can be increased to three as well ex: consider school structure. Intially , consider , student id is key , later , should be searchable even with key name , later with grade.
You have been given an array of int as input. Return true if there exist 2 numbers in the array whose sum is equal to the sum of the rest of the numbers in the array.
twoSum({2,11,5,1,4,7}) = true (11+4 = 2+5+1+7)
Given a String with print all the possible combinations of the all the characters in the string as a string for Example
"abc" is the input the you should print the below:
abc
ab
ac
a
bc
b
c
There is one invisible string which is actually a blank string.
Design a telephone directory for large ppl (he gave example like design for India). fields will be , first name , last name , number . this should be searchable with first name , last name , number as welll.
later added more complexity like do the same for organisation where even it contains designations. so this should be searchable with designations.
Find the consecutive number of 1s in a unsigned integer?
eg suppose you are given 67 the binary equivalent for this is 0b1000011
so here 1 is consecutively appeared 2 time maximum
so 2 is the answer
Write a longest palindrome substring in a given string using recursion..
int LPS(char* str, int n)
Write a longest common string function using recursion
int LCS(char* str1, int m, char* str2, int n)
interviewer was not interested in iterative approach
function prototype should be same
. If a/b is recurring like 10/3, print 10/3 as 3.(3), 16/6 as 2.(6), 3227/555 as 5.8(144)
Let's say you have 10,000 servers, each with a billion integers. How do you find the median ?
Let's say you have 10,000 servers, each with a billion integers. How do you find the median?
Given a string that contains exactly a single pair of parenthesis, return parenthesis and their contents, so "xyz(abc)123" yields "(abc)". etc.
Conditions:
1)No variable allowed
2)Collections not allowed
3)Regex, String.indexOf() not allowed.
Given a string that contains exactly a single pair of parenthesis, return parenthesis and their contents, so "xyz(abc)123" yields "(abc)". etc.
Condition: You are not allowed to use a variable anywhere, Regex is not allowed.
Given a string that contains exactly a single pair of parenthesis, return parenthesis and their contents, so "xyz(abc)123" yields "(abc)". etc.
Condition: You are not allowed to use a variable anywhere.
hi guys ..hows the adobe recuitment first round will be like
Write a program to replace each element of an array with a number present on the right side of the element such that the number is least greater than the element. If there is no greater number replace it with -1
e.g : 8, 58, 71, 18, 31, 32, 63, 92, 43, 3, 91, 93, 25, 80, 28
ans : 18, 63, 80, 25, 32, 43, 80, 93, 80, 25, 93, -1, 28, -1, -1
I gave the obvious o(n^2) solution. He asked to optimize it.
Write a program to replace each element of an array with a number present on the right side of the element such that the number is least greater than the element. If there is no greater number replace it with -1
e.g : 8, 58, 71, 18, 31, 32, 63, 92, 43, 3, 91, 93, 25, 80, 28
ans : 18, 63, 80, 25, 32, 43, 80, 93, 80, 25, 93, -1, 28, -1, -1
You have 5 data sources. There is a program which calls these data sources and returns a count value.
You need to speedup this program. How do you do that?
This is a sample code
int count = getCount(ds1);
if(count < 100 )
count = count + getCount(ds2);
if(count < 100)
count = count + getCount(ds3);
if(count < 100)
count = count + getCount(ds4);
if(count < 100)
count = count + getCount(ds5);You have 5 data sources. There is a program which calls these data sources and returns a count value.
You need to speedup this program. How do you do that?
int count = getCount(ds1);
if(count < 100 )
count = count + getCount(ds2);
if(count < 100)
count = count + getCount(ds3);
if(count < 100)
count = count + getCount(ds4);
if(count < 100)
count = count + getCount(ds5);
Sherlock rolls a N faced die M times. He adds all the numbers he gets on all throws. What is the probability that he has a sum of K.
A N faced die has all numbers from 1 to N written on it and each has equal probability of arriving when dice is thrown.
2
1 5 2
2 3 2
For first testcase, sum=1,2,3,4,5 are all equally probable. Hence probability is 0.2.
For second testcase:
(1,1), (1,2), (1,3), (2,1), (2,2), (2,3), (3,1), (3,2), (3,3) are all possible ways.
Out of these 1 has sum 2. So 1/9 is the answer.
replace all occurrence of particular word with another word of larger length. Solution should be inplace can do copy only one time.
e.g.
Gandhi was born in 1969. Gandhi was from gujrat.
replace gandhi with mahatma
Implement a method called printNonComments() which prints out a extract of text with comments removed.
For example, the input:
hello /* this is a
multi line comment */ all
Should produce:
hello
all
You have access to a method called getNextLine() which returns the next line in the input string.
Write a java program for Fibonacci series...in this format
{1, 1, 2, 3, 5, 8, 13, 21, 34, 55,}print {1,1,#,3,5,#,13,21,#,55}instead of even numbers print #..how to solve this question
String="welcome bangalore" i want erolagnab welcome how to reverse this string..can anyone knows pls answer this one.
What data tructure should be used for designing a postal system
Two finite, strictly increasing, integer sequences are given. Any common integer between the two sequences constitute an intersection point. Take for example the following two sequences where intersection points are
printed in bold:
First= 3 5 7 9 20 25 30 40 55 56 57 60 62
Second= 1 4 7 11 14 25 44 47 55 57 100
You can ‘walk” over these two sequences in the following way:
1. You may start at the beginning of any of the two sequences. Now start moving forward.
2. At each intersection point, you have the choice of either continuing with the same sequence you’re currently on, or switching to the other sequence.
The objective is finding a path that produces the maximum sum of data you walked over. In the above example, the largest possible sum is 450 which is the result of adding 3, 5, 7, 9, 20, 25, 44, 47, 55, 56, 57, 60, and 62
this is the same problem which I saw in SPOJ Problem Set
int[] a1={1,3,5,7} int[] a2={3,6,8,9} int[] a3={}...
Merge first two arrays in a sorted order result put it in third array output will be{1,3,3,5,7,8} write a code for this one?
I recently, appeared for second phone interview with CloudEra, the interviewer asked me to
write a function which takes in an array of integers and returns the highest positive product
possible by multiplying 3 distinct numbers. NO SORTING is ALLOWED
PS: Please write a solution in JAVA or Python. (Not interviewer request)
example:
[1, 3, 5, 2, 8, 0, -1, 3]
=> 8 * 5 * 3 = 120
[0, -1, 3, 100, -70, -5]
=> -70*-50*100=350000
write a java program consider a text file,that file is having N number of lines.how to print last N lines..
string[][] names={{"perk","parker"},{"jhon","raj"},{"ram","lakshman"}};
write a java program print lastname,then firstname in sorted order without using string.compareTo,collections.sort,arrays.sort
I was asked to design an application that sends a message to two friends if they come within two miles of each other.
I gave him a solution indicating the data structures used to maintain the friend list and model of the solution .
He pointed out the cons of the solution and I modified the data structure
I was asked to design an application that sends a message to two friends if they come within two miles of each other.
I gave him a solution indicating the data structures used to maintain the friend list and model of the solution .
A quadra tree is a tree where each node has atmost 4 child nodes(similar to a binary tree which has atmost 2 child nodes).
A monitor screen (black and white) is represented by a qudra tree in the following way:
case 1: If the entire screen is white then the value in the root node is white.
similarly if the entire screen is black then the root stores black.
case 2: If the screen is neither completely black nor white then the screen is divided into 4 quadrants and the node has 4 child nodes each representing one of the quadrants.( the screen is recursively divided into subscreens).
Now given two screens represented by two quadra trees, return a quadra tree which represents the overlapping of the two screens.( assume when white and white overlaps results in white,black and white overlap results in black , black and black overlap results in black).
algo and code both have to be given.
Write a java program to evaluate given arithmetic expression to get maximum possible answer. ( Expression will contain only 3 type of operations +,-,* ). it will not contain any brackets. so the order of operator precedence will not be there. any part of the expression can be executed in any order to get the maximum possible ans.
The digits of a number come from a stream digit by digit. At any point tell whether the number formed from the digits so far is a multiple of 3
what container will you choose if you should store numbers and check whether certain number is already stored?
Design a logger class for your application? The log messages can be printed in a log file.
Suppose you may want to provide the user the option whether he wants to print the messages in a log file or into database at runtime. How would you modify your earlier design?
A new Kindle feature is being developed to rank customers based on their reading speed.
A customer's "reading speed" is the maximum number of pages they have read in a single minute over the previous 10 minutes. Every minute, we will log the customer's current page, which can be used to calculate this speed. For example:
Current Time: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14,15]
Current Page: [0, 5, 6, 8,12,15,17,21,24,27,29,31,37,42,49,52]
Current Speed: [0, 5, 1, 2, 4, 3, 2, 4, 3, 3, 2, 2, 6, 5, 7, 3]
"Reading Speed": [0, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 4, 6, 6, 7, 7]
We want to produce separate leaderboards for each book. Each customer will only read one book at a time, but multiple customers may read the same book.
Every minute, the "updateReadingSpeeds" method will be called to report each customer's reading progress. Please implement this method:
void updateReadingSpeeds(String customerID, String bookID, int pageNumber)
At any time, we should be able to request the full leaderboard for any book. Please implement the "printLeaderboard" method:
void printLeaderboard(String bookID)
The output should be CSV printed to standard output, like:
Customer ID,Reading Speed,Rank
Customer 1,5,1
Customer 3,4,2
Customer 2,4,3
Customer 5,2,4
*The updateReadingSpeeds method will be called every minute for every customer.
*CustomerID will uniquely identify a customer, bookID will uniquely identify a book
*Page numbers are integers between 0 and 1000000, and will never decrease over time.
*Customers who "tie" with the same reading speed can be ranked in any order.
char p[133];
snprintf(p, sizeof(p), "This is a %.4s\n", "test
GARBAGE DATA");
But i am geting This is a 4s??????????????
Given A Binary Tree of size n , Find Out a Matrix M[n][n], where M[i][j]=1 if i is predecessor of j, else M[i][j]=0.
Try to do in better than O(N^2) time.
(Bar Raiser Round)
Divide the array(+ve and -ve numbers) into two parts such that the average of both the parts is equal.
Input:
[1 7 15 29 11 9]
Output:
[15 9 1 7 11 29]
Explanation:
The average of first two elements is (15+9)/2 = 12, average of remaining elements is (1+7 +11 +29)/4 = 12
/*
Write an algorithm that brings all nonzero elements to the left of the array, and returns the number of nonzero elements.
Example input: [ 1, 0, 2, 0, 0, 3, 4 ]
Example output: 4
[1, 4, 2, 3, 0, 0, 0]
* The algorithm should operate in place, i.e. shouldn't create a new array.
* The order of nonzero elements does not matter
*/
Given
{
//"Restaurant Types"."[categoryNames]"
"American" : "[Burger, French fries, Potato Chips]",
"Italian":"[Pizza,Bread Sticks, Potato Chips]"
}Assume this kind of data is given as input and loaded into your choice of Data Structure.
Using Category name return the no of resturarnt type. Ex: if i/p is Potato Chips, O/P should be : 2 (American and Italian).
Please mention your Data structure and logic.
Write testcases for thermostat(that controls room temperature) that connects to web and server
Write a detailed test plan for the Language Detection API available at http://detectlanguage.com
Difference between struct and class.
When would you use one over the other
What is padding? Do both struct and class have padding
Explain the underlying working of how inherited function gets invoked. So if Dog and Cat, inherited from Animal, inherit Eats. How does the right Eats get called for Dog/Cat
private inheritance vs composition
When would you use private inheritance
What is a static function? Explain in detail
Implement an atoi function in C++
Difference between threads and process.
When would you use one vs the other
Where on the stack are values stored for their local variables?
If there are two threads each with two local variables, where will these variables be stored
Reverse the alternate level nodes of the binary tree.
a
/ \
b c
/ \ / \
d e f g
/ \ / \ / \ / \
h i j k l m n o
Modified tree:
a
/ \
c b
/ \ / \
d e f g
/ \ / \ / \ / \
o n m l k j i h
How to count the number of The sum of two numbers that are even in an unsorted array with negative, positive integers ? in O(N) ?
You have a rabbit who wants to cross a river by jumping over the various rocks in it. All the rocks are in a straight line and the distance between them is also given. Your rabbit can only perform jumps of specific lengths. You have to output the minimum number of jumps required to cross the river (if possible). Rabbits can jump both in forward and backward direction.
The number of rocks is M and the number of possible jump lengths is N.
For e.g. M=4 , N=2,
distance between m1-m2= 1
m2-m3= 2
m3-m4 =1
rabbit can perfrom jump of length 3 and 1.
output= 2 (minimum jump to cross the river)
• Suppose we need a service to perform certain task every day at some specified time. How do we ensure that everyday at the specified time the service will do that task?
Given a singly linked list, modify the value of first half nodes such that 1st node’s new value is equal to the last node’s value minus first node’s current value, 2nd node’s new value is equal to the second last node’s value minus 2nd node’s current value, likewise for first half nodes.
(No extra memory to be used)
I recently had an generous offer that I turned that based mainly on my answer to this question in PHP.
Write an algorithm to generate all possible combinations of a product code based on all available product options. Each option has a code/slug that make up the product code. For example shoes:
style: 001, 002, 003, etc...
color: red, blue, white, etc...
size: 7,8,9,10,etc...
gender: m,f
etc: etc...
I recently had a generous job offer based mainly on my answer to this question in PHP.
Write an algorithm to generate all possible combinations of a product code based on all available product options. Each possible option value has a code/slug that make up the product code. For example, shoes:
style: 001, 002, 003, etc...
color: red, blue, white, etc...
size: 7,8,9,10,etc...
gender: m,f
etc: etc... number of options and possible values for each option have to be flexible, though pretty finite
first combination: shoes001red7m
I used a few loops inside loops, 4 I believe, I don't remember now.
Gaurav is a 12 year old student who’s fractured his leg and lower back in a bicycle accident and
is on a bed rest for the next 2 months. He keeps himself busy by watching television on his
Skycast DTH. While watching the television, one day he decided to play a small game, where
he has to identify the minimum number of clicks required to surf a given set of channels in a
sequence. He quickly decided that it makes for an interesting problem to solve using a software
program, (oh, forgot to tell you that he likes to code when he is not busy with his school work).
Your task is to write the software program (using any of the programming language choices
given), before Gaurav can do it himself, we think he is going to take 2 hours, so you think you
can beat the 12 year old in solving this, we think so! Your time starts now!
Obviously the program has to take the following instructions and constraints into account.
Instructions
There are 13 buttons on his remote: 10 buttons for the numbers (0-9), an "Up Channel" button,
a "Down Channel" button, and a "Back" button:
● The number buttons allow you to jump directly to a specific channel. (Ex: to go to
channel 63 by typing “6”, “3”.)
● The "Up Channel" button increments the current channel to the next higher viewable
channel, unless the current channel is the highest viewable channel, in which case it
rolls over to the lowest viewable channel.
● The "Down Channel" button decrements to the next lower viewable channel, unless the
current channel is the lowest viewable channel, in which case it rolls over to the highest
viewable channel.
● The "Back" button reverts to whatever channel was on the television before the current
channel. (Ex: If channel 1 is viewed, then channel 100, then when Back is pressed, the
television will go to channel 1.)
Gaurav can get from one channel to the next in one of the two ways:
● Clicking any combination of "Up Channel", "Down Channel", and "Back" buttons.
● Keying in the numbers to the channel. Gaurav will never combine "Back" and number
buttons when moving from one channel to the next.
Gaurav’s parents have set some parental control on some channels on Gaurav's television.
These channels are not viewable, so they are skipped by the "Up Channel" and "Down
Channel" buttons.
Given a list of channels to view, the lowest channel, the highest channel, and a list of blocked
channels, your program should return the minimum number of clicks necessary to get
through all the shows that Gaurav would like to watch.
Input
Page 2
Your program has to take 3 inputs for each test case, the first input will contain two space
delimited numbers, these will form the lowest channel and the highest channel. The next input
will contain the number of blocked channels followed by sequence of blocked channels (again
space delimited). The first number in the input will contain the number of inputs The last input is
the sequence of channels that Gaurav must view (in order). Again, the first number will contain
the number of inputs
Notes:
● Unit tests are mandatory, so please ensure that the code you submit has automated unit
tests and you adopt TDD principles (as it applies to this problem statement)
Sample Input
Test Case #1
1 20
2 18 19
5 15 14 17 1 17
Test Case #2
103 108
1 104
5 105 106 107 103 105
Test Case #3
1 100
4 78 79 80 3
8 10 13 13 100 99 98 77 81
Test Case #4
1 200
0
4 1 100 1 101
Sample Output
Output for Test Case #1:
7
Output for Test Case #2:
8
Output for Test Case #3:
12
Output for Test Case #4:
7
Constraints
● The lowest channel on the television will be greater than 0, and less than or equal to
10,000.
● The highest channel on the television will be greater than or equal to lowest channel,
and less than or equal to 10,000.
● The list of channels that are blocked on Gaurav's television. All the channels in this list
will be valid channels (greater than or equal to lowest channel, less than or equal to
Page 3
highest channel). Duplicates may be ignored. The blocked list can be maximum of 40
channels.
● The sequence that Gaurav must view contains between 1 and 50 elements, inclusive. All
channels in this sequence are not in the blocked list and are between lowest channel
and highest channel, inclusive.
Two robots land with their parachutes on an infinite one-dimensional number line. They both release their parachutes as soon as they land and start moving. They are allowed only to make use of the following functions.
I. moveLeft() // robot moves to left by 1 unit in 1 unit time
II. moveRight() // robot moves to right by 1 unit in 1 unit time
III. noOperation() // robot does not move and takes 1 unit time
IV. onTopOfParachute() // returns true if the robot is standing on top of either of the parachute, else false
V. didWeMeet() // returns true if the robot meets to the other robot, else false
Write a function in order to make the robots meet each other. Robots will be executing the same copy of this function.
You have an array like ar[]= {1,3,2,4,5,4,2}. You need to create
another array ar_low[] such that ar_low = number of elements lower
than or equal to ar in ar[i+1:n-1].
So the output of above should be {0,2,1,2,2,1,0}
Time complexity : O(nlogn)
use of extra space allowed.
Swap 2 nodes in a Binary tree.(May or Maynot be a BST)
Swap the nodes NOT just their values.
(preferably in Java please..(My requirement not theirs :p))
ex:
5
/ \
3 7
/ \ /
2 4 6
swap 7 and 3
5
/ \
7 3
/ / \
6 2 4
You have an array of integers(size N), such that each integer is present an odd number of time, except 3 of them(which are present even number of times). Find the three numbers.
Only XOR based solution was permitted.
Time Complexity: O(N)
Space Complexity: O(1)
Sample Input:
{1,6,4,1,4,5,8,8,4,6,8,8,9,7,9,5,9}
Sample Output:
1 6 8
Can anyone provide implementation of Suffix tree and trie?
Given an unsorted array of integers, you need to return maximum possible n such that the array consists at least n values greater than or equals to n. Array can contain duplicate values.
Sample input : [1, 2, 3, 4] -- output : 2
Sample input : [900, 2, 901, 3, 1000] -- output: 3
Traveler wants to travel from city “A” to city “D”.
There is a path from city “A” to city “D”.
Path consists of steps, i.e. travel from city “A” to city “B”.
Path is encoded as sequence of steps.
Sequence is in incorrect order.
Your task is to restore order of steps in the path.
Input (unordered sequence):
C -> D
A -> B
B -> C
Output (Correctly ordered list which represents path):
A, B, C, D
Implement following API:
class Step {
String start;
String finish;
};
class Node {
String value;
Node next;
}
List<String> findPath(List<Step> steps) {
}You are given an array A = [1, 2, 3, ..., n]:
How many sequences (S1) can you get after exact k adjacent swaps on A?
How many sequences (S2) can you get after at most k swaps on A?
An adjacent swap can be made between two elements of the Array A, A[i] and A[i+1] or A[i] and A[i-1].
A swap otherwise can be between any two elements of the array A[i] and A[j] ∀ 1 ≤ i, j ≤ N, i ≠ j.
Input Format
First and only line contains n and k separated by space.
Output Format
Output S1 % MOD and S2 % MOD in one line, where MOD = 1000000007.
Constraints
1 ≤ n ≤ 2500
1 ≤ k ≤ 2500
Sample Input
3 2
Sample Output
3 6
Explanation
Original array: [1, 2, 3]
1. After 2 adjacent swaps:
We can get [1, 2, 3], [2, 3, 1], [3, 1, 2] ==> S1 == 3
2. After at most 2 swaps:
1) After 0 swap: [1, 2, 3]
2) After 1 swap: [2, 1, 3], [3, 2, 1], [1, 3, 2].
3) After 2 swaps: [1, 2, 3], [2, 3, 1], [3, 1, 2]
==> S2 == 6
Given a Binary Search tree of integers, you need to return the number of nodes having values between two given integers. You can assume that you already have some extra information at each node (number of children in left and right subtrees !!).
You are given information about hotels in a country/city. X and Y coordinates of each hotel are known. You need to suggest the list of nearest hotels to a user who is querying from a particular point (X and Y coordinates of the user are given). Distance is calculated as the straight line distance between the user and the hotel coordinates.
Make a function that shows the common elements in two arrays. Part 2: With duplicates (small explanation). Part3: without duplicates
Answer:
int[] intersect(int[] array1, int[] array2){
if(array1.lentgh == 0 || array2.length == 0)
return {};
Set<Integer> set = new HashSet<Integer>();
for(int i = 0; i < array1.length ; i++){
set.put(array1[i]);
}
List<Integer> list = new ArrayList<Integer>();
for(int i = 0;i < array2.length ; i++){
if(set.contains(array2[i])){
//map.put(map.get(array2[i])-1); //short explanation of how to do it with dupplicates
set.remove(array2[i]);
list.add(array2[i]);
}
}
return list.toArray();
}Having a table Genre with two colums (Id, Genre) make an SQL Query that finds the Ids with the genre Action and Comedy. (those will have multiple lines for each Id)
Answer:
select g.id from (select id from genre where genre = 'Action') x, genre as g where g.id = x.id and genre = 'Commedy'How would you do to sort different files. All the data does not fit in memory.
Answered: Merge sort like method, where you sort each file. For the end merge, read some data from each file (make sure you have at least one from each file) and sort them
Divide an array of positive negative integers numbers, print all subsets that have sum = k
No can be repeated but subsets should be unique
Input:- {2,3,4,1,3,2,6,-1}, Sum = 5
Output:-
2,3
4,1
4,2,-1
6,-1
3,2,1,-1
2,2,1
3,3,-1
may be some more but i want all should be unique
3,2,1,-1 and 2,-1,1,3 are same so i not want u print it two time ...
you cannot store these subsets and later u compare for unique or not using previous generated subsets..
Given a tree having N vertices and N-1 edges where each edges is having one of either red(r) or black(b) color. I need to find how many triplets(a,b,c) of vertices are there, such that on the path from vertex a to b, vertex b to c and vertex c to a there is atleast one edge having red color.
It should be noted that (a,b,c), (b,a,c) and all such permutation will be considered as the same triplets.
EXAMPLE : Let N=5 and edges with colors are as follow :
1 2 b
2 3 r
3 4 r
4 5 b
Here answer will be 4.
EXPLANATION : (2,3,4) is one such triplet because on all paths i.e 2 to 3, 3 to 4 and 2 to 4 there is atleast one edge having read color. (2,3,5), (1,3,4) and (1,3,5) are such other triplets.
What is composite key? How it differs from candidate key?
Write a function to convert a string (char* that contains a number, e.g. "586") to int.
2*45min interviews back-to-back. First interviewer asked two questions.
Given n*m fields of O's and X's, where O=white, X=black, for example
OOOXOOO
OOXXOXO
OXOOOXO
Return the number of black shapes. A black shape consists of one or more adjacent X's (diagonals not included). In the example, the answer is 3.
Write code (I chose C++). What data structures would you use to store the input, and what to use for the shapes? What is the runtime complexity?
Given a complete binary tree, Find a Max element
Given an unsorted list with each node having a random pointer to another node, sort the list such that each node points to the next node in the list (n1->n2->n3).
Given an integer Q and an array A of size N, can we figure out the answer to each of the Q queries?
Each query contains two integers x and y, and we need to find whether the value find(x,y) is odd or even:
find(int x,int y)
{
if(x>y) return 1;
ans = pow(A[x],find(x+1,y));
return ans;
}
Here pow(a,b)=ab.
Example: Let N=3, the array be [3,2,7], and the query be x=1 and y=2. Now do find(1,2)=9, which is odd so answer is odd.
I know the basic approach, but what if queries can be as large as 105 and same is with N?
Its given that 1≤x, y≤N, and x≤y
Write a program that gives count of common characters presented in an array of strings..(or array of character arrays)
For eg.. for the following input strings..
aghkafgklt
dfghako
qwemnaarkf
The output should be 3. because the characters a, f and k are present in all 3 strings.
Note: The input strings contains only lower case alphabets
In Mathematics each number has one special number, which it supports, chosen as follows. It counts the number of ones in its own binary representation, and adds this count to itself to obtain the value of the number it supports. That is, if j(m) means the number of ones in the binary representation of m, then m supports m+j(m). For example, the number eight (1000 in binary) supports nine, whereas nine supports eleven.
However, in this way not all the numbers get supported; some are left without support, and we call these numbers bleak. For example since one supports two, two supports three and three supports five, there is no number less than four, which would support four, so four is bleak.
Your task is for a given number recognize if it is bleak or supported by some number.
Design a two player battleship game to be played over internet
Suppose you have a telephone directory. There You have telephone number and names. Names can be duplicate but telephone number will be unique, No use some datastructure in such a way that when we give telephone number it will return the corrosponding name, Again when we give a name, it will retrieve all the entries with same name and their corresponding telephone number from the datastructure. Complexity should be minimum as much as possible. I gave a solution of O(n) for the second case, but they did'nt agree this to be optimised.
Lakshmi is a primary school teacher. She wants to give some laddus to the children in her class. All the students sit in a line and each of them has a rating score according to his or her usual performance. Lakshmi wants to give at least 1 laddu for each child. Children get jealous of their immediate neighbors, so if two children sit next to each other then the one with the higher rating must get more laddus. Lakshmi wants to save money, so she wants to minimize the total number of laddus.
Tip: Please understand the question clearly and pay good attention to below provide - sample input and output - completely in order to arrive at correct solution.
Input
The first line of the input is an integer N, the number of children in Lakshmi's class. Each of the following N lines contains an integer indicates the rating of each child.
Ouput
Output a single line containing the minimum number of laddus Lakshmi must give.
Explanation
Sample Input
3
1
2
2
Sample Ouput
4
Explanation
The number of laddus Lakshmi must give are 1, 2 and 1.
How would you sell me Amazon Web Services RDS, s3 and ec2?
This is an interview question which i faced: Write a function in C# to remove duplicate characters from word irrespective of its case. For example: Input: ADJaoSS Output: ADJoS. Can anyone please help me with this function?
Given the following two tables
Student{studentID, name, address} //<studentID> is primary key
StudentSubject{subjectID, studentID} //<subjectID, studentID> are primary key
course{subjectID, subName} //<subjectID> is primary key.
Question: write a SQL query to list all students who did not enroll in any subject. (sub query is not allowed)
Suppose you have a million integer numbers.
Return all possible values of a,b and c such that
a+b+c<=d.
d will be provided to you.
ex: if the numbers are 1,2,3,4,5,6,7
and d=7
[1,2,3]
[1,2,4]
[1,2,3] will be same as [1,3,2] and [3,2,1]...
follow up:
Return all such parts that satisfy the above condition if d is not provided.
Given a number, you have to replace digits of the number with a given character 'a' and print all such possible strings(replacing only 1 digit or more at a time). The constraint is that no 2 consecutive digits should be replaced.
How we can implement final classes in C++, We should be able to create
.object but other class if try to inherit compiler should flag error...
When compiler fails to write a copy constructor for u even if u not write any copy constructor
Test t1 = Test();
Test t2 = t1; //error
1)When Compiler fail to write a default assignment operator for u
Test t1 = Test();
Test t2 = Test();
t1 = t2 // this give error if user not write a assignment operator
For a given vector containing even and odd num write a function so all odd elements got erased from vector
Extending this question further
For a given stl::map of even n odd ints write a logic so all even elements got erased.
i looking best code for this...
what will output of this
#include <iostream>
#include<algorithm>
using namespace std;
class Sum
{
private:
int s;
public:
Sum(int x):s(x)
{
}
int getSum()
{
return s;
}
void operator()(int p)
{
s = s + p;
}
};
int main()
{
cout << "Hello World" << endl;
int arr[] = {1,2,3,4,5,6,7,8};
Sum obj = for_each(arr,arr+7,Sum(1000));
cout<<obj.getSum()<<endl;
return 0;
}int main()
{
int x = -7;
int y = -2;
cout<<(x%y)<<endl;
return 0;
}
int main()
{
int x = 7;
int y = -2;
cout<<(x%y)<<endl;
return 0;
}
int main()
{
int x = -7;
int y = 2;
cout<<(x%y)<<endl;
return 0;
}
#include<iostream>
using namespace std;
int main()
{
int x = -7;
int y = -2;
cout<<(x%y)<<endl;
return 0;
}
#include<iostream>
using namespace std;
const char* fun()
{
const char* str = "This is test string";
return str;
}
int main()
{
const char* p = fun();
while(!p != '\0')
{
cout<<*p;
p++;
}
return 0;
}
Is there any problem with this code...what will be the output of this problem?? if there is any error then why...and if it work fine then why??
How and where to initialize const data member in C++, if you did not initialize it in member initializes list?
Below is the hash :
c31843b739e61ec7bf5f63da93d97d0321f42f0304750c41ae88a3b04727ba21f5c7061e7517101f3b8f2fa53d3a32960c03e3b78112619b2674802429d831fcdb38fdff909bdcb6a2da09a462e35671c310e4954d1578a0194cf86b6e4b2550a58893d756c0d557451c487546b7a908377d5cc436daa6bd0cebbd8a2593db7ccc536aab131d8ca8c4c5daf505190d6e61a0c80b65d337e839c4c77c5a7f90daaf5aed8aff7d43876194d64a289cf42aedd977889120178500f4ef48aa3cdae78b1a4383d8f4f136f02c1d2d122f8819d8a2c66de0240ce2416ba43b0346de0450684f874fdb5d34b698e8a93ee45e15e8994c361f387a9fe94107b2d11f743cc34843d9031a7a0c01976ecf1f88056a6fa1b40744a88a37ee95fc66058370def144c686d692f012b07f56c497955a8fc40a51652240928e3c899aca8791a8e5f345f65745cfbec16f0446bafaa3e0593ab2d69e02b2562029178779e835cc933c99d289cc96b51f63a0c8abb01bc9df2659480fbb2f17f3b0817c807d222abbd58d1c60037ec5e35c06f2080a3b593928be4af515573024bdf5603f9696de81af8b065f6e2976a2efaa097d6613431c162c7acb00f7892acb3a2ffef15701bd
First, A series of string prefixes is generated with lengths increasing by 2. For example, if our secret word was "abcxy@hoho.com", we would generate:
ab abcx abcxy@ abcxy@ho ... ...... abcxy@hoho.com
Then, for every prefix s, following hash H is computed: md5(md5(e) + s + md5(s)) [where + is the string concatenation operator and e is "xxxxx@hehu.xxx.edu"].
Finally, all hash strings H are concatenated to form the long hash above....
For example, for abcxy@hoho.com, - the hash would be computed as
md5(md5('xxxxx@hehu.xxx.edu') + 'ab' + md5('ab')) +
md5(md5('xxxxx@hehu.xxx.edu') + 'abcx' + md5('abcx')) +
md5(md5('xxxxx@hehu.xxx.edu') + 'abcxy@' + md5('abcxy@')) +
...
For the sake of simplicity, you can assume that secret word only contains alphanumeric characters and these 4 characters: _ . @ +
and using e= xxxxx@hehu.xxx.edu, the hash is generated.
and we have to find out that secret word (from the hash).
These are the details I have researched:
Hash from MD5 is always 128 bits/16 bytes/32 ascii characters long
Collision Attack
Birthday Attack
Any Hidden paterns in the given hash
I am looking for a direction here. The given hash is exactly 896 letters long. Any ideas or redirects are much appreciated. Thanks.
Write a method that takes a given string and replaces all occurrences of one string with another string, returning the number of replaces made. For instance given the string “Microsoft” if you were to replace all occurrences of “ic” with “MSFT” the result would be “MMSFTrosoft” with a return value of 1. As part of a final solution please provide unit tests done as well as any test cases ran. Please note that you may not use String.Replace or string::replace depending upon the language you use; you must write this functionality yourself.
Implement a class that does string manipulation by overloading the following operators: <<, >>, = and ==. For example consider the following code:
StrShift example;
example = “Microsoft”;
printf(“\”example << 2\” results in %s\n“, example << 2);
In the above code the output would be “ftMicroso” which shows the last two characters of the string “Microsoft” rotated to the left of the string. Please note that state is maintained so two calls of example << 1 would give the same end result as calling example << 2 once. Consideration will be given to correctness, design, code readability as well as any unit testing. As part of a final solution please submit test cases you used to verify correctness in addition to any unit tests done.
Write a class that represents a minimal heap. The heap class should at a minimum support the following methods:
- AllocTinyHeap() which should initialize the heap with a given amount of bytes
- DeleteTinyHeap() which frees all memory associated with the heap
- TinyAlloc() which allocates a given number of bytes on the heap if there is room
- TinyFree() which frees a specific location on the heap
You may define whatever parameters are necessary for the above methods as well as write any additional methods. Overall consideration will be given to correctness, design, code readability as well as any unit testing done. As part of a final solution please submit test cases you used to verify correctness in addition to any unit tests done.
why do we need pipes. how do they help in interprocess communication?
1. why do we use fork and when do we use fork in realtime products?
any interview questions on system programming for seniors
Given a string with multiple spaces write a function to in-place trim all spaces leaving a single space between words
e.g.
_ _ _ Hello _ _ _ World _ _ _
Hello _ World _ _ _ _ _ _ _ _ _
I was asked to design a trading system, where there will be no of buyers and sellers will transact. The system need to have low latency, the buyers will quote no of shares, company name, price they want to buy, the sellers will quote the price they want to sell for given company, and no of shares. The system has to match the buyers and sellers and transact. This is more of design question.
I was thinking in terms of a hashmap kind a structure where the key will hash to the given company, and then there will be buckets for no of shares for buyers, with different buckets for prices, the idea is to look up in memory sellers, if a match is found then make the transaction. If the in memory data exceeds a limit implement a caching, and push the older data to the persistent store. The guy was'nt convinced this was a good design. Can someone suggest how is real time trading systems implemented, do they go for low latency queues.
How to maintain a regression Test suit?
how to put my program on remote server so that it will run automatically when i initiate it .
can any one tell me how to test LEAP for Linux client
Write a method that takes a given string and replaces all occurrences of one string with another string, returning the number of replaces made. For instance given the string “Microsoft” if you were to replace all occurrences of “ic” with “MSFT” the result would be “MMSFTrosoft” with a return value of 1.
2. Write a method that takes a given string and replaces all occurrences of one string with another string, returning the number of replaces made. For instance given the string “Microsoft” if you were to replace all occurrences of “ic” with “MSFT” the result would be “MMSFTrosoft” with a return value of 1.
I've heard this from someone, guess it is not the full question but this question is quite familiar:
Given some kind of operating system that run Tasks. Every task comes with a certain time it should run. For example first task need to run 15 seconds, after 2 seconds comes another task that need to run another 30 seconds, after 7 seconds comes another task need to run another 2 seconds, etc.
You have a scheduler that runs every second and check which task need to be run and run them.
You don't have system clock and need to find a solution without it.
How would you implement it?
You are given a string S and a set of n substrings. You are supposed to remove every instance of those n substrings from S so that S is of the minimum length and output this minimum length.
Eg:
S- ccdaabcdbb
n=2 - substrings-- ab, cd
Output: 2
Explanation:
ccdaabcdbb -> ccdacdbb -> cabb -> cb (length=2)
Can someone help me with the algo?
difference btw find & locate command in unix?
we have 2 tables A & B. write a query to get just the non matching data from B table using joins
how to get data for a column when you do not know the database & table of the column?
how to check that constraints are applied on table ?
how to find out total no. of columns by SQL?
public class WithoutConditional {
static void callme(String s) {
System.out.println("string");
}
static void callme(Object s) {
System.out.println("object");
}
public static void main(String[] args) {
callme(null);
}
}The above code prints "string". Even if we change the order of the methods.
My question is why it doesn't print "object" as String is also instanceof Object. Passing null as argument shouldn't print "object" ???
A string can contain 0 to n(input) number in sorted form find all the transition point.
given a binary tree and a leaf node. holding a leaf node and whole tree falls down such that it is the new root of the tree. return the modified tree.
Base class is given you need to stop exposing the base class methods without touching the base class at all.
The boggle game - given a 2d array of characters
Evaluate a given mathematical expression, taking into consideration the BODMAS rule. The expression contains no brackets.
The Boggle game.
Serialize and deserialize a tree.
Given a tree - not necessarily a binary tree - the serialize method should create a string for the tree. The deserialize method should be able to reproduce the same tree using the string derived from the serialize method.
Basically, serialize() takes in a tree and returns a string, deserialize() takes in a string and returns the tree.
How many occurrences of a given search word can you find in a two-dimensional array of characters given that the word can go up, down, left, right, and around 90 degree bends?
Ex:
Count of occurrences of SNAKES
S N B S N
B A K E A
B K B B K
S E B S E
The answer is 3.
Write a program for that question.
Design multiple stacks in a Single one big int array as efficient as possible ( real world example multiple process function stacks creation and deletion in memory of linux os )
What happens when you enter URL in browser.
Write a program to convert a decimal number into binary your code should work on both big endian and small endian machine. U have given a variable which tell u whether machine is big endian or small endian
U have given 10 files each having 1 million integer in sorted order, physical memory have size of 3 million suggest method to extract 1 million integer in sorted form efficiently.
Given a graph, if we were to print all nodes within k hops of a given node, which algorithm would we use, the answer to this was obviously a Breadth first search. He followed it up asking, if one were to use Depth first search instead to code this problem instead, one would encounter bloated running times for Graphs with certain attributes (Perhaps Dense graphs or some such). Describe what types of graphs would a DFS algorithm falter with and why.
Given a floor of dimensions 2 x W and tiles of dimensions 2 x 1, write code to find the number of ways the floor can be tiled.
You are given a sequence of black and white horses, and a set of k stables numbered 1 to k. You have to accommodate the horses into the stables in such a way that the following conditions are satisfied:
a. You fill the horses into the stables preserving the order of horses. For instance, you cannot put for horse 1 into stable 2 and horse 2 into stable 1. You have to preserve the ordering of horses.
b. No stable should be empty and No horse should be left unaccommodated.
c. Take the product (number of white horses * number of black horses) for each stable and take the sum of all these products. This value should be the minimum among all possible accommodation arrangements.
Given a value (in double) return its square root.
You are asked to code an Android game that shows this board
+——————————+——————————+
|1 | 2|
| | |
| ♠ | ♣ |
| +———+———+ |
| | ♥ | ♠ | |
+——————+———+———+——————+
| | ♦ | ♣ | |
| +———+———+ |
| ♥ | ♦ |
| | |
|3 | 4|
+——————————+——————————+Where the numbers are text but the spades, diamond, etc are graphics.
The four squares in the center of the board are buttons. When you press any of these buttons, a popup shows buttons from 1 to 4. You have to click the number that makes your original button to match the quadrant whose symbol is the same.
So, in the figure, if you pressed the spades button, then you should press the button labeled 1. If you pressed the heart button then you should press 3, etc.
When you press the buttons correctly, the figure button is swapped properly so it gets in the quadrant containing that figure, and disabled for further push.
If the number button were incorrect instead, the original figure button is swapped with the figure button at the quadrant whose number you erroneously clicked.
The game finishes when all figure buttons are in their correct quadrants. Last but not least, the figure buttons are initially placed randomly.
Describe how you'd put this board in a layout that doesn't distort the figures neither in quadrants nor in buttons.
Explain how you'd code the most important portions of this game.
Given a List of Students that are already sorted based on names, write a function to return list of students that is sorted based on grade (four possible grades are a,b,c and d). If two students has same grade, they should be sorted internally based on name.
I have written a code based on bucket sort. Something like this. Not sure whether this is optimal.
public List<Student> sortByGrade(List<Student> students)
{
List<Student> aGradeStudents = new LinkedList<Student>();
List<Student> bGradeStudents = new LinkedList<Student>();
List<Student> cGradeStudents = new LinkedList<Student>();
List<Student> dGradeStudents = new LinkedList<Student>();
for(Student st : students)
{
switch(st.getGrade())
{
case 'a' :
aGradeStudents.add(st);
break;
case 'b' :
bGradeStudents.add(st);
break;
case 'c' :
cGradeStudents.add(st);
break;
case 'd' :
dGradeStudents.add(st);
break;
};
}
List<Student> sortedStudents = new LinkedList<Student>();
sortedStudents.addAll(aGradeSudents);
sortedStudents.addAll(bGradeSudents);
sortedStudents.addAll(cGradeSudents);
sortedStudents.addAll(dGradeSudents);
}Given an array of sorted numbers, find the index of first occurrence of the given number.
Code a function that receives a string composed by words separated by spaces and returns a string where words appear in the same order but than the original string, but every word is inverted.
Example, for this input string
@"the boy ran"the output would be
@"eht yob nar"Tell the complexity of the solution.
Design an HTTP downloader that caches results and doesn't block execution (i.e., enables simultaneous downloads).
Code a function that gets two strings representing binary numbers (so the only possible characters are '1' and '0', and returns a third string representing the sum of the input. The input strings don't necessarily have of the same length.
Tell the complexity of the solution.
Code a function that receives an array with duplicates and returns a new array keeping the original order of the elements but with the duplicates removed.
For example, if the input were
@[ @"dog", @"cat", @"dog", @"fish" ]the output would be
@[ @"dog", @"cat", @"fish" ]Tell the complexity of the solution.
String d1="7 dec 2012";
String d2="15 dec 2012";
String d3="12 dec 2012";
String d4="16 dec 2012";
String d5="16 dec 2012";
String d6="24 dec 2012";
days between d1 and d2 is: 9
days between d3 and d4 is: 1 (12 dec to 15 dec counted in d1 and d2, don't count overlapping days)
days between d3 and d4 is: 8 (16 dec counted in d3 and d4, don't count overlapping days)
now final output should be: 9 + 1 + 8=18
If you are told to test a requirement wchich you are not understanding then what will be your approach to analyze that requirement? How will you understand that requirement?
If are told to test a requirement and you are not able to understand that requirement then , what will you do to understanding a requirement? What will be your approach?
how to use perl to write a script to deal with the comments in a C++ file?
let's say a file a.cpp, and it contains several comments. You have to remove the comments.
we know that in C++ there two kinds of comments // and /* */
i was trying to use the regex, but later i was stuck when i found that these comments can appear in a string, say "aaa // bbb", then it will be another situation.
can someone help me with this case?
any ideas will be helpful.
There are 3 points in space forming a triangle. There is another point, Can you find whether the 4th point lies inside the triangle. Can you solve this using the concept of Area?
Lets say you have a number n and there is an array that has size = n+1.There is one element repeated in the array. Can you find that number?
Input spec: n = 5
int arr[6] = {3, 1, 4, 4, 5, 2};
Output: 4
Lets say you have a number n and there is an array whose size is n-1. Array contains numbers in between 1 to n and all unique numbers.
But one number is missing from the array as its size is n-1. Can you find that missing number in the array?
Input Spec: n = 5
int arr[4] = {3, 1, 4, 5};
Output: 2
Lets say you have been given a number n. You need to find out all prime numbers starting from 1..to..n ?
How would you design a game for chess ? Think in terms of object oriented design. What all classes and behaviors you could think of ?
Given n, find the smallest number for which product of the digits is n, if no such number exists, print -1
Note: Digits can only be split as single digits, i.e., 132 can’t considered as 1 * 32 or 13 * 2, it would only be 1 * 3 * 2
Eg. Answer for 36 would be 49
We have 25 horses and we need to find top 5 fastest horses irrespective of order, in a race only 5 horse can run. how many min races required to know top 5 horses...out of top 5 ordering not matter...u not need to tell which is fastest which is at second position.....
Given a binary tree, write a method to determine shortest distance between two nodes. A node does not have a pointer to its parent
Given a binary tree, write a method to determine shortest distance between two two nodes. The node does not have a pointer to its parent
Given a graph, write a method to check if it is bipartite
How do you swap bits at indexes i & j of a 32-bit memory word?
remove a character in a string to make palindrome?
Suppose an Archeologist is visiting Africa, who don't know the native language. There are two tribe, one of those always speaks the "Truth" and another one always speaks "Lie". Suppose you are in front of three such people, of course you don't know them as truth/lie speaking tribe. You asked a question, and the 1st one replies in his native language, which you don't know, then 2nd tells that the 1st person is lying(in english) and the third person tells that 2nd person is lying(in english).
Which tribe does the 3rd person belongs?
Need to write Boundary Value Analysis cases - Scenario is , A book seller takes order of minimum of 5 books and if any person is ordering more then 100 books he will get discount of 20%.
What will be the boundary values for the above case.
find subsets in array whose sum equal to a given number??
example: S={1,3,5,2,7} and k=10, answer is {1,2,7},{3,5,2},{3,7} , i need best code for this
Print permutations of a string.
I started with the recursive answer. He asked me the complexity. (Had no idea). But is was large
Then he asked me, if i could optimise it. I said i could sense this can be done using DP. Could not get how to do it though.
I had quick perm code, but dint understand it(saw it night prev to interview) so dint answer that.
implement bool isFactorialDivisible( int x, int y)
Return true if x! is divisible by y
else return false
MsExcel columns has a pattern like
A B C … Z
AA AB AC…. AZ BA BB … ZZ
AAA AAB
A has code 1
Z has code 26
AA has code 27
AAA has code 626
given a number return a column name as string
Given a continuous stream of strings, maintain strings such that duplicate are eliminated on the fly. The interviewer wanted working code. So coded the solution during the interview and emailed it to him 10 mins after.
So if you get “Ted”, “John”, “Mark”, “Ted”, “David”, at the moment in
time, the list should contain John, Mark, David
Foo was not amongst the most brilliant students of his class. So, he has some pending exams to clear. As the exams are approaching, this time he vowed to pass in all of them. This will only happen if he is not under stress. Foo's stress can be calculated using a simple function called Foo_function which depends upon the time for which Foo studies continuously .
Foo_funtion is defined as follows:
F(t)=A(t^3)+B(t^2)+C*(t)+D, F(t)<=10^18
where A,B,C,D belong to the set of prime numbers. t is the time in minutes for which foo studies continuously.
As foo is not very good at solving cubic equations, he seeks your help to find out the maximum number of minutes for which he can study continuously without taking stress. Help him find t such that F(t+1) > K, and F(t) <= K, where K is the maximum stress Foo can bear.
Input:
The first line of the input contains a single integer T denoting the number of test cases. each test case consists of a single line containing 5 space seperated positive numbers a, b, c, d, K.
Output:
for each test case, output a single integer t denoting the maximum time for which foo can study continuously without taking stress.
Constraints:
1 <= T <= 10^4
A, B, C, D belong to a set of prime numbers such that F(t) would never exceed 10^18
t >= 0
1 <= K <= 10^18
Sample Input (Plaintext Link)
2
2 2 2 2 10
2 3 5 7 1000
Sample Output (Plaintext Link)
1
7
Explanation
In the 1st test case for t = 2 foo will be under stress because F(2)=30 > K, therefore he can study for a maximum time of 1 minute without having stress.
In the 2nd test case for t = 8 foo will be under stess because F(8)=1263 > K, therefore he can study for a maximum time of 7 minutes continuously without having stress.
Time Limit 5 sec(s) (Time limit is for each input file.)
Memory Limit256 MB
Source Limit1024 KB
Quest: create a Random number generator without using the java in build Random class?
public class GenerateRandomNumbers {
public static int seed = 10;
public void generateInt(int num){
seed = num;
for(int i=1;i<num;i++){
seed = ((int)System.nanoTime()%(i));
if(seed<=0)
seed = ((int)System.currentTimeMillis()%i);
System.out.println(seed);
}
}
public static void main(String[] args) {
new GenerateRandomNumbers().generateInt(20);
}
}
its a class to generate random numbers but the problem is It always starts with 0...!
Can someone add some more to this code.??
Given a integer N, print the decimal form of 1/2n.
Example:
N=1, print 0.5
N=2, print 0.25
Adding leading/unsignificant zeroes will lead to wrong answer. Example, printing 0.50 instead of 0.5 in above case will lead to wrong answer.
Input and Output:
First line contains T, the number of testcases. Each testcase consists of N in one line.
Print required answer in one line for each testcase.
Constraints:
1 ≤ T ≤ 100
1 ≤ N ≤ 200
Sample Input (Plaintext Link)
2
2
1
Sample Output (Plaintext Link)
0.25
0.5
Explanation
You need to print output in decimal form only. There is no limit on number of decimal digits in output.
So correct output of 100 will be "0.0000000000000000000000000000007888609052210118054117285652827862296732064351090230047702789306640625"
Time Limit1 sec(s) (Time limit is for each input file.)
Memory Limit256 MB
Source Limit1024 KB
Use smart ways to find prime factors and then arrive at the result for large A & B in input. Bruteforce won't work.
Given A,B print the number of pairs (a,b) such that GCD(a,b)=1 and 1<=a<=A and 1<=b<=B.
Input:
First line contains an integer T, the number of testcases. Each of next T lines contains two space separated integers denoting Aand B.
Output:
Output T lines, each containing single integer, the required output for each test-case.
Constraints:
1 <= T <= 10
1 <= A <= 10^5
1 <= B <= 10^5
Sample Input (Plaintext Link)
1
3 2
Sample Output (Plaintext Link)
5
Explanation
1,1
1,2
2,1
3,1
3,2
Time Limit5 sec(s) (Time limit is for each input file.)
Memory Limit256 MB
Source Limit1024 KB
- there is a large filed (dimensions are specified)
- Given a list of rice varieties that can be grown on a square plots (of 2X2) in the large field.
- Given the dimensions of the large field we can find out the number of individual plots that can be cut out (rows and columns)
- Each variety has its own pollination period specified by start and end date.
- We have to assign plot to each variety such that there is no intersection in pollination period of neighbouring varieties.
- Neighbouring variety is the variety grown in the adjacent plot. Any plot can have a max of 8 neighbours
- The output is a 2D matrix representation, where each cell is a plot. Each plot is assigned at most one variety of rice.
- Each variety of rice can be assigned to at most one plot
- Maximise the number of varieties used. (minimise the number of vacant plots)
eg:
name,start_date,end_date
V1,11Sep,15Sep
V2,13Sep,20Sep
V3,1Oct,4Oct
V4,25Sep,30Sep
- it is ok if some plots are left empty
- no_of_rice_varieties <=1000
You are give a circular pizza with 3n pieces of pizza , each piece of pizza has different volume, The task is to eat n pieces of pizza such that the total consumed volume of pizza is the maximum, condition when the user chooses a piece of pizza he has to discard its immediate 2 neighboring pieces, the pizza is circular and every time we eat and discard there are new neighbors being formed per piece.
For ex:
pizza one : 2 1 1 2 9 1 10 1 9
pizza two: 1 9 2 2 9 1 1 10 1
pizza three: 1 9 2 2 9 1 1 10 10
Suppose the pizza was divided into 2n pieces, would your approach to find the maximum volume change from that of 3n pieces?
Given a string (for example: "a?bc?def?g"), write a program to generate all the possible strings by replacing ? with 0 and 1.
Example:
Input : a?b?c?
Output: a0b0c0, a0b0c1, a0b1c0, a0b1c1, a1b0c0, a1b0c1, a1b1c0, a1b1c1.
Table 1: Parents -> (int id, int age)
Table 2: Children -> (int id, int age, int parent_id)
Get the parent id, his/her oldest and youngest children ids.
Table 1: Parents -> (int id, int age, int Child_id)
Table 2: Children -> (int id, int age, int parent_id)
Get the parent id, his/her oldest and youngest children ids.
Hi guys, is it possiblesend data(audio) stream to my PC from my mobile through bluetooth? if yes how can i achive the same?
Thanks in advance
given 10 files (text files) each of size of 900 Mb. givena another file named "hello". match the contents of this file with other 10 file and return the file whose contents closely match with the contents of file "hello"
Given a BST, find out the minimum length form root to leaf with sum S. Note that:
a) Path from root to leaf node.
b) Sum of node of the path is S.
c) if multiple such path exist, print minimum length path.
d) What is advantage of BST rather than BT used for this algorithm, how it improve the performance. in BST, is it required to explore both side ?
Implement thread-safe circular queue that has 2 methods Read & Write n bytes.
The entire design and implementation was open for discussion.
Discussion went for locking, multi threading, boundary cases, all sets of issues related to multi threading..it was quite intense..
remove a character from the string which does not come simultaneously in c
for example, given the string str1 = "120jdvj00ncdnv000ndnv0nvd0nvd0" and the character ch = '0', the output should be 12jdvj00ncdnv000ndnvnvdnvd. That is, the 0 is removed only wherever it occurs singly. this code is not working
remove a character from the string which does not come simultaneously in c
for example, given the string str1 = "120jdvj00ncdnv000ndnv0nvd0nvd0" and the character ch = '0', the output should be 12jdvj00ncdnv000ndnvnvdnvd. That is, the 0 is removed only wherever it occurs singly. this code is not working
Given the following directory structure:
org
| -- Robot.class
| -- ex
|-- Pet.class
|
|-- why
|-- Dog.class
And the following source file:
class MyClass {
Robot r;
Pet p;
Dog d;
Which statement(s) must be added for the source file to compile? (Choose all that apply.)
A. package org;
B. import org.*;
C. package org.*;
D. package org.ex;
E. import org.ex.*;
F. package org.ex.why;
G. package org.ex.why.Dog;Starting at the 0 (zero) index, you need to "jump" through a one-dimensional array (zero based index) of true/false values. True is a place you can land on (if desired) and false is a place you must jump over (cannot land on). The array can be very very long.
Your "velocity" indicates how many spots (or array indexes) you advance with every jump. For example, if you have a velocity of 2 and are currently at index 4, after the jump, you will be at index 6. Before each jump you can increase your velocity by 1, decrease your velocity by 1, or keep the same velocity. You can only go forwards.
You start at index 0 (zero), with a velocity of 1. This means that for the very first jump, you can keep the same velocity and move to index 1, or increase velocity by 1 (to a velocity of 2) to move to index 2. On this first jump, you can't decrease your velocity as that would make your velocity 0 (zero) and you wouldn't move. Now that you've jumped, you can again increase, decrease, or keep your velocity the same, then jump again.
As an example, let's say you increased your velocity to 2 and jumped. You're now at index 2 with a velocity of 2. You can:
1) decrease your velocity to 1 and jump to index 3.
2) keep your velocity at 2 and jump to index 4.
3) increase your velocity to 3 and jump to index 5.
Remember, you can only and on an index if it's "true". You are successful if you can get past the last index. Implement a function to determine if the rabbit can make it across given the field (array).
Here is a field that the rabbit cannot cross:
$field = array(true, true, false, true, false, true, false, false, false, true);
Here is a field that the field can cross:
$field = array(true, true, false, true, false, true, true, false, false, true, false);
Write a function, for a given number, print out all possible way to make up that number eg: 2 - 1 1,2
Find if there is a cycle in a list of parent-child tuples.
You are given a list of tuples
(a,b) => a is parent of b
(b,c) => b is parent of c
(c, d) => c is parent of d
(d, a) => d is parent of a ----> Cycle detected..
Implement a Java method.
You are given parent-child relationships. Your goal is to find find the data is cyclical.
(a,b) => a is a parent of b
(b, c) => b is a parent of c
(c, a) => c is a parent of a ... Oops! Cycle found!
public bool hasCycle(List<String, String> input);
Divide an array into 2 subsequence such that the absolute difference of their sum is minimum
You are given a 2D grid in which each cell is either empty, contains an entry “D” which stands for Door, or an entry “W” which stands for wall (Obstacle). You can move in any of the four directions from each empty position in the grid. Of course you cannot move into a cell that has “W” in it. You need to fill each empty cell with a number that represents the distance of the closest door to that cell.
A furniture can be made of material like metal, wood, .... Also there are different furniture types chair, table, sofa. A wood furniture should be tested against choaking. metal furniture is tested against fire, etc. Design these in OOAD.
There are N nodes. Each node has a non negative integer value. Define a optimistic algorithm which ensures that all node has all other node's value.
Constraint: While a node is sending data to another data, it can't receive data, vice versa.
Hi , I went for Wells Fargo Testing interview, They asked
If we are told to perform only regression testing on a software application and not to do sanity testing , then what could be the nature of your software application.
You are given several thousand - two member tuples of compatible entries.
Your goal is to find the longest list of compatible entries
i.e.
(a,b) => a is compatible with b
(b,d) => b is compatible with d
(d, e) => d is compatible with e
Longest list a,b,d,e
Here is a small program which will be of my help.
Please code it in JAVA. If you are successful, please send me the code as early as possible by tomorrow.
If you are not able to get, please send me the update.
The Definition is given as below:
1. A File contains string for Example: GCDNPQACKSPEGF...FIM
2. Read each character from this file and ASSIGN the values as below:
A,C,S = 3
F,D,N,T= 4
P,F,Y = 9
M,E,G = 2
Q,H,I,K,R,L = 6
3. AFTER ASSIGNING CHECK THE FILE FOR MAPPING
4. Sum THE VALUES in that sequence for Eg: 2+ 3+ 4...... = SUM = 60
5. FIND THE total LENGTH of the sequence for E: L = 20
6. Find the AVERAGE A = SUM/L =60/20 =3
7. USE THE PATTERNS as triplets from the same file as given below AND CALCULATE EACH PATTERN'S WEIGHTAGE as for Eg:
GCD = 2 + 3 + 4 = 9 (G = 2, C=3, D=4 from the mapping)
CDN = 3+4+4 = 11
...........
for all possible patterns
8. FinD THE MAXIMUM OF ALL THE PATTERN'S WEIGHTAGE
So, the o/p should be : Average -->
Triplet and its Weightage as :GCD : 2 + 3+ 4 = 9 for all possible triplets
Maxi Weightage -->
Write a java program to find out 5000th number in the fibonacci series.?
For example:
5th number is 5.
6th number is 8.
10th number is 55.
5000th number is ????.
A matrix will be given which contains nos. and dots. will have to output another matrix in which the nos. are surrounded by single loop. the value of each number in a matrix equals the number of lines surrounding it.
Empty spaces in matrix/dots may be surrounded by any number of lines.
When completed, the solution forms a single continuous loop with no crossings or branches.
Value of each no. should connect the adjacent dots horizontally and vertically so that the lines form a simple loop with no loose ends based on the above rules.
eg
input Matrix
1.31.3
...3..
.3.21.
.02.1.
..2...
2.23.3
output Matrix
- -
1 .|3|1 .|3|
- - | - |
|. . .|3|. .|
| - - -
|.|3|. 2 1|.
- - - _
. 0 2 .|1 .|
- - - -
|.|.|2 . .|.
| - - -
|2 . 2|3|. 3|
- - - - -
i tried making rules and then call the function to make lines, but couldnt succeed in gettin desired output.
for any queries please comment
A matrix will be given which contains nos. and dots. will have to output another matrix in which the nos. are surrounded by single loop. the value of each number in a matrix equals the number of lines surrounding it.
Empty spaces in matrix/dots may be surrounded by any number of lines.
When completed, the solution forms a single continuous loop with no crossings or branches.
Value of each no. should connect the adjacent dots horizontally and vertically so that the lines form a simple loop with no loose ends based on the above rules.
eg
input Matrix
1.31.3
...3..
.3.21.
.02.1.
..2...
2.23.3
output Matrix
- -
1 .|3|1 .|3|
- - | - |
|. . .|3|. .|
| - - -
|.|3|. 2 1|.
- - - _
. 0 2 .|1 .|
- - - -
|.|.|2 . .|.
| - - -
|2 . 2|3|. 3|
- - - - -
i tried making rules and then call the function to make lines, but couldnt succeed in gettin desired output.
for any queries please comment
You have a LinkList with each node having Next node and Other node and Data.
i.e. Class Node
{
Node Next;
Node Other;
int Data;
}
Next pointer always points to next node and Other node can point to any other node in the list or can be pointing to null/nothing or can point to self.
Write program to copy this link list to a new list with proper Next and Other pointers.
find the pivot position in a sorted and rotated array,it may includes duplicates,negative value,i need complete code..?
Multiple threads are running in my program. Exception occurs in one of the thread. There is no exception handling done.
What will happen to my program? Will it terminate the complete program? What will happen to other threads?
`#include<stdio.h>
int main(void)
{
int s[4][2] = { {1234,56}, {1212,33}, {1434,80}, {1312,78} };
int (*p)[2];
int i, j, *pint;
for( i=0; i<=3; i++)
{
p = &s[i];
pint = (int*)p; //Q. My Question is why we are required to type cast here. ?
printf("\n");
for( j=0; j<=1; j++)
{
printf("%d",*(pint+j));
}
}
return 0;
}`
Why we are required to perform the typecasting at the comment line ?
What is the exact difference between
1. Pointer to an array int (*ptr)[10]; and
2. Array of pointers int *ptr[10];
Write code to read from a file and build datastructure that helps you query products based on their category, title, author etc.
ItemNo , Product No (unique), Title, Author, Category
1 , 00000001, Cracking Coding Interview, Gayle Laakmann McDowell , Books > Business, Finance & Law > Careers > Job Hunting
2 , 000002, The Art of Captaincy, Robert James, Books > Biography > Sport > Cricket
You have given M array each of size n all array are sorted separately write a program to make a big sorted array of size m*n . during discussion he told me to prove many lemma like height of tree is log(n)( for n elements) sum of n natural number is (n*n+1)/2 and many more. He modified problem many times don’t use extra space do it in space etc.
Write a program to convert a decimal number into binary your code should work on both big endian and small endian machine. U have given a variable which tell u whether machine is big endian or small endian
U have given 10 files each having 1 million integer in sorted order, physical memory have size of 3 million suggest method to extract 1 million integer in sorted form efficiently.
U have given 10 files and you have given a string suggest data structure which ll facilitate efficient search of string in the file if string appears more than ones in that case u have to print line number and file in which they appear.
You are given a sequence of black and white horses, and a set of k stables numbered 1 to k. You have to accommodate the horses into the stables in such a way that the following conditions are satisfied:
a. You fill the horses into the stables preserving the order of horses. For instance, you cannot put for horse 1 into stable 2 and horse 2 into stable 1. You have to preserve the ordering of horses.
b. No stable should be empty and No horse should be left unaccommodated.
c. Take the product (number of white horses * number of black horses) for each stable and take the sum of all these products. This value should be the minimum among all possible accommodation arrangements.
Given the range of the numbers like [A, B] , Tell the number of the numbers where the difference between sum of the even place digits and the sum of the odd place digits is one..
Please do not tell the method using brute force, or saving all the results beforehand.
Given a 2D (Rectangular) grid of points. You need to find the shortest path from a given source point to a destination point. You can only move up or right. Now among these points, there a few special points from which you can directly jump to the diagonally opposite point (Top-Right diagonal). You are granted a function which when invoked on the point returns 1 if it is a special point and 0 if it is not.
Given a floor of dimensions 2 x W and tiles of dimensions 2 x 1, write code to find the number of ways the floor can be tiled. Any suggession for this?
Sort an almost sorted Array. An almost sorted Array being an Array in which a number is at the most k positions away from its position in the sorted Array.
Find the position of displaced element
Machine Coding:
Design and code application similar to IPL website.
1. There are players who belong different teams [CSK, RCB,etc].
2. User can create their own team from the player set
3. When a match happens, there are possible outcome in each ball [one run, six, wicket, run-out, etc]
4. on each outcome, players involved will get points [eg: six = batsman 5 points, wicket = batsman minus 5 and bowler +5, etc]
5. Based on outcome, the user created team also should be able to calculate his points.
6. Solution should be working code, extensible and performance.
Let's say a website attracts a lot of traffic . How would you find at what instant of time (milliseconds or seconds , assume as you want) the traffic was super high ? What data structure would you go for and why ?
A man goes to a hardware shop and asks for price of an item. The shop keeper replies that the item is "one for $1".
The man gives the shop keeper "$3 for 600". What did the man buy for his newly painted house?
The cost of a parallel processing is primarily determined by:(A) Time complexity (B) Switching complexity(C) Circuit complexity
A locked file can be:(A) accessed by only one user(B) modified by users with the correct password(C) is used to hide sensitive information(D) both (B) and (C)
Find the K most frequent strings from a large data that can't fit into the memory in one go. Lets say there is a data of 200GB but available RAM memory is 1GB only.
Find minimum number of steps to reach the end of array from start (array value shows how much you can move).
A 2D matrix with +/- numbers , write a program to return Max sum of submatrix.
Write a program to return minimum number of swaps required to convert this binary tree into a BST.
R4 | Q2. Given a BST, find out the minimum length form root to leaf with sum S. Note that:
a) Path from root to leaf node.
b) Sum of node of the path is S.
c) if multiple such path exist, print minimum length path.
d) What is advantage of BST rather than BT used for this algorithm, how it improve the performance. in BST, is it required to explore both side ?
e) Write working codes for it.
Round 4( 2h 30 min)
===================
Q1. You are given a Text, where all space, full stop and all punctuation mark is removed. You want to reconstruct the text by putting spaces between words.
A dict is given and following API < bool isInDect(word) > is also given.
a) Decide if the text can be converted a sentence with valid words or NOT.
b) Find how many way you can do the reconstruction of the text
c) Find what is the minimum number of space can be used for this reconstruction.
d) For case (c) find out the indexes where you suppose to put a space.
e) Now recover the text to sentence in place .
Subsequent Question:
1. Why Greedy technique will not work for this
2. yes ! Backtracking will work, what is the problem of using backtracking
3. Illustrate and explain how the solution is contracted from the Dynamic table.
4. Write the correct working code for (c),(d),(e).
R3 | Q4. You have a file with million words in it. Find most frequent 10 word in that file. Node that you can store all word in memory.
(Note : Min-Heap + List )
R3 | Q3. What the different issue in multi-threading ? What is the difference between mutex and semaphore.
R3 | Q2. Reverse a 32-bit integers. write code for it.
Round 3:(1.h 15min)
===================
Q1. In a plane n points (X and Y) is given. How will you find out maximum co-liner points. Extend this algorithms. it for point(x,y,z) in 3D plane.
R2 | Q3. Design a Chip-Encryption system. Which will do following operation:
1. Take a word from user
2. Encrypt the word by some Private or public key cryptography or any other algo.
3. Transmit the encrypted word by TCP or UDp or SSL.
Design the class diagram using OOD. Which design pattern you are using to achieve this.
R2 | Q2. You have a dictionary of words. Given a word, print all anagram are in dictionary . State the data structure to be used to solve this problem.
Round 2:(1.h 15min)
===================
Q1. Given a sorted array having duplicate elements,how would you find first index of a given element in O(nlogn).
Write code for it. Change the condition to find out last index of that elements.
[ Hint Binary search]
R1 | Q2. Find an element in a sorted rotated array in O(nlogn ) complexity.
Round 1: (1 h)
==============
Q1. Design a Garbage collector like java. How would you detect depended reference loop ?
Hist : Class design, Cycle detection algorithms for disjoint graph( List of connected graph)
You have a rectangular chocolate bar that consists of width x height square tiles. You can split it into two rectangular pieces by creating a single vertical or horizontal break along tile edges. For example, a 2x2 chocolate bar can be divided into two 2x1 pieces, but it cannot be divided into two pieces, where one of them is 1x1. You can repeat the split operation as many times as you want, each time splitting a single rectangular piece into two rectangular pieces.
Your goal is to create at least one piece which consists of exactly nTiles tiles. Return the minimal number of split operations necessary to reach this goal. If it is impossible, return -1.
Complete the function getMinSplit, which takes in 3 integers as parameters. The first parameter is width of the chocolate, the second is height of the chocolate and third is nTiles, the number of tiles required.
Constraints
- width will be between 1 and 109, inclusive.
- hight will be between 1 and 109, inclusive.
- nTiles will be between 1 and 109, inclusive.
Example 0
5
4
12
Returns: 1
You can split the chocolate bar into two rectangular pieces 3 x 4 and 2 x 4 by creating a single vertical break. Only one break is necessary.
Example 1
12
10
120
Returns: 0
The chocolate bar consists of exactly 120 tiles.
Example 2
2
2
1
Returns: 2
Example 3
17
19
111
Returns: -1
Example 4
226800000
10000000
938071715
Returns: 2
Human gene consisting of four nucleotides, which are simply denoted by four letters, A, C, G, and T.
Your job is to make a program that compares two genes and determines their similarity as explained below.
Given two genes AGTGATG and GTTAG, how similar are they? One of the methods to measure the similarity of two genes is called alignment. In an alignment, spaces are inserted, if necessary, in appropriate positions of the genes to make them equally long and score the resulting genes according to a scoring matrix.
For example, one space is inserted into AGTGATG to result in AGTGAT-G, and three spaces are inserted into GTTAG to result in -GT--TAG. A space is denoted by a minus sign (-). The two genes are now of equal length. These two strings are aligned:
AGTGAT-G
-GT--TAG
In this alignment, there are four matches, namely, G in the second position, T in the third, T in the sixth, and G in the eighth. Each pair of aligned characters is assigned a score according to the following scoring matrix.
* denotes that a space-space match is not allowed.
The score of the alignment above is (-3)+5+5+(-2)+(-3)+5+(-3)+5=9.
Of course, many other alignments are possible. One is shown below (a different number of spaces are inserted into different positions):
AGTGATG
-GTTA-G
This alignment gives a score of (-3)+5+5+(-2)+5+(-1) +5=14. So, this one is better than the previous one. As a matter of fact, this one is optimal since no other alignment can have a higher score. So, it is said that the similarity of the two genes is 14.
You are expected to complete the function getDNAAlignment, which takes in two strings as argument.
Constraints
Length of both strings will not exceed 1000.
Both string will be non-empty strings.
strings will only consists of character from set {'A', 'C', 'G', 'T'}
Sample Input 00
AGTGATG
GTTAG
Returns: 14
Sample Input 01
AGCTATT
AGCTTTAAA
Returns: 21
You are a coin collector in a country, where the silver coin denominations runs from 1 to 1000000. You have N coins with you with various denominations.
Apart from the silver coins, the country also issues gold coins which can be used as any value. With the given silver and gold coins, find out the maximum continous denomination streak you can achieve.
For example, if you have 4 silver coins of value 2, 3, 5 and 9 and 1 gold coin. You can have a maximum streak of 4 coins by using the gold coin as value 4.
Input format.
The first line contains 2 integers, S and G. S is the number of silver coins you have and G is the number of gold coins you have. S lines follow, each line is the value of the corresponding silver coin
Output format:
One integer, representing the maximum streak you can have using the coint.
Sample Input 1
4 1
2
3
5
7
Sample Output 1
4
Draw a graph as a graph. Assume there is graphics library to draw lines and all. Just tell how will you order the vertices such that the edges don't intersect and they seem ordered.
Need to implement something like pastebin wherein you paste some text, you are given an url. The url can be used anywhere to access the text.
Various problems, features and design of this architecture were discussed.
There are N lanes, and the speed of each lane is given. There are many cars in all the lanes and the start position and the length of each car and its corresponding lane is given. There is a frog which an do 2 functions: wait() or jump().
Find if there is a path for the frog to go from lane 1 to lane N without getting hit by any of the moving cars.
Write an algorithm to find the ‘next’ node (e.g., post-order successor) of a given node in a binary tree and binary search tree
a.) where each node has a link to its parent.
b.) without parent pointer
implement 2 versions of the algorithm: 1.) binary tree 2.) BST
Endian conversion little - big endian
WAP , In SLL delete nth node from end.
struct st{
int a;
char *ptr;
}obj;
assign : a=10;
ptr="Hello world";
Write a test case for the Amazon App store.
Since there are so many functionality in Amazon App store, do I just make a smoke test or do I need to go all out and make testcase that will cover everything.
There is a byte array which contains the character of one byte and two bytes. One byte character has range 0 to 127 and first character of 2 byte character is 128 to 255 and second byte character has range 0 to 255. Now, two pointers are given, one points to the start of the and another points to somewhere else.
Tell which character 2nd pointers points to?
You are given very huge file , with each line containing a single word. We have to give the count and word which is repeated most. I answer of using TRIE data structure to hold the word. I am reading a word at a time and incrementing the counter if i am getting the same word. I am keeping a global max count to keep the max count and the word. Complexity will be O(total letters in the file);
Given a binary search tree (BST) with each node having some value. You have to compute for each node the summation of all nodes whose value is greater than the current node.I have used the DFS kind of algorithm.
Dictionary<node,bool> visited = new Dictionary<node,bool>();
int Traverse(node n )
{
if(node.Right == null)
if(node.Left != null && !visited(node.Left))
Traverse(node.Left);
return node.value;
node.Summation = Traverse(node.Right);
if(node.Left != null && !visited(node.Left))
Traverse(node.Left);
return node.Value + node.Summation;
}Given a self-balancing tree (AVL), code a method that returns the median.
(Median: the numerical value separating the higher half of a data sample from the lower half. Example: if the series is
2, 7, 4, 9, 1, 5, 8, 3, 6
then the median is 5.)
Create the data structure for a component that will receive a series of numbers over the time and, when asked, returns the median of all received elements.
(Median: the numerical value separating the higher half of a data sample from the lower half. Example: if the series is
2, 7, 4, 9, 1, 5, 8, 3, 6
then the median is 5.)
Model the data structure for a component that would have these two methods:
@interface SampleHandler {
- (void)addNumber:(NSNumber*)number;
- (NSNumber*)median;
}Justify your decisions. Calculate the complexity of each method.
i) Explain Polymorphism
ii) Output of the below code snippet :-
public class ParentTest {
public int x = 0;
public void print() {
System.out.println("In Parent");
}
}
public class ChildTest extends ParentTest {
public int x = 1;
public void print() {
System.out.println("In Child");
}
public static void main( String args[] )
{
ParentTest s = new ChildTest();
System.out.println(s.x);
s.print();
}
}How to draw graph for the given set
G={(4,6,0,7),(2,0,8,5),(12,3,0,0),(0,0,9,8)}
Given the following linked list: 1 -> 2 -> 3-> 4-> 5-> 6 reverse the list each N nodes. eg. if N = 3 the output should be 3-> 2-> 1-> 6-> 5-> 4. Also provide a mechanism to prevent errors. For the same example, if N = 4, the result should be: 4-> 3-> 2-> 1-> 5-> 6 (The last two nodes can't be reversed)
implement the 'cd' command i.e. given a function cd('a/b','c/../d/e/../f'), where 1st param is current directory and 2nd param is the sequence of operations, find the final directory that the user will be in when the cd command is executed
Given a set of 21 tasks = {A, B,....Z} except I, O, U, X and Q. Each task requires 4 hours of processing. Except for tasks E, Y, P, R, W that require 8 hours of processing.
You have 3 machines to process these tasks = T1, T2, T3. T1 and T2 are available everyday for 8 hours. T3 is available only on Mon, Wed and Fri for 8 hours.
You are given 3 lists that indicate the dependency list among the tasks.
L1 = A->R->K->M (eg A can be completed if R is completed, R can be completed only if K is completed etc.)
L2 = N->G->V->E->Z->H
L3 = C->F->Y->D->J->P->T->S->W->B->C (cycle)
Each task needs one machine for its duration to complete.
Tasks cannot be resumed. Which means the 8 hour tasks cannot be executed over 2 days.
Each machine can process only one task at any time.
T1, T2 and T3 can process different tasks in parallel.
You are starting your schedule on a Wednesday.
Machines can be scheduled only during weekdays.
The first Monday in your schedule is a downtime for all the machines.
Given these constraints, write a program that generates a schedule between the tasks and machines such that all the tasks are completed at the
earliest.
find the minimum number of swaps to convert one string into another ?ex:kamal amalk
In synchronous request from browser how do you get results if you have to access 2 different databases
In assembly line situation, how do you pass a job from thread1 to thread2 to thread3?
in a web request you want to send results to the browser/client only if the caching operation goes success. how do you accomplish this.
Given a linked list with next and high pointers, populate high pointers to the next higher node, inplace and O(n).
Asked to explain the abstract factory design pattern along with its drawbacks (if any)?
Given N matrix production (A1*A2*A3...*AN), different matrix can have different dimensions but they satisfy the production requirement. For example, A1 is 2x3, then A2 can be 3x4 but not 5x2. When a 3x2 matrix products a 2x4 matrix, the total number of number production required is 24. How to reduce the total number of number production when calculating (A1*A2*A3...*AN)?
There are 4 types of coins (25 cent, 10 cent, 5 cent and 1 cent). Given a number, return the minimum number of coins whose sum equals to this number. What about the 4 types of coins changes to (25, 10, 6, 1)? Write code.
Given N matrix production (A1*A2*A3...*AN), different matrix can have different dimensions but they satisfy the production requirement. For example, A1 is 2x3, then A2 can be 3x4 but not 5x2. When a 3x2 matrix products a 2x4 matrix, the total number of number production required is 24. How to reduce the total number of number production when calculating (A1*A2*A3...*AN)?
Design an LRU Cache with constant lookup, i.e, searching and updating should all happen in O(1) time. Assume a method of calculating the least recently used page is already given. Just implement the searching and updating logic which takes constant time.
Consider sorted singly linked list having following nodes
10->30->50->70->NULL
You are given pointer to node 50 and a new node having value 40. Can you inserted node 40 correctly in the list maintaining the ascending order?
Design a Pool class and write down any interfaces that you could think? A Pool class could be a Thread Pool or memory pool, that can store resources.
Given a linked list: 5 -> 4 -> 3 -> 2 -> 1, produce the following output: 4 -> 2 -> 0 -> 2 -> 1 by substracting the 1st node with nth node, the 2nd with nth -1 node, etc... Only apply the stated action on the first half of the list
Write a program to count the number of numbers between two numbers a, b that have the sum of their bits equal to a fibonacci number.
For example between 15 and 17 there are two numbers that have sum of bits equal to a fibonacci number.
15: 1111 sum=4
16: 10000 sum=1 (fibonacci)
17:10001 sum=2 (fibonacci)
So the output will be 2 in this case.
Test case -
Input 15 & 17
Input 173 & 10000003210005
The interviewer asked this to code in 5 hours in any programming language & mail him the full working program.
Write a program to output the number of consecutive trailing zeros in the factorial of a number?
For example:-
Input - 5!
Output - 1 (Since 5! = 120 & 120 has 1 trailing zero in the end)
Given a array int a[]={2,5,1,9,3,7,2,8,9,3} and the no. of swap operations.We are allowed to do swap operations.
swap constraint: exchange only adjacent element.
Find the max number that can be formed using swap operations.
public static int[] maximize(int arr[],int swapsAllowed);Given a table of the form:
1 A,B,C,A,B
2 A,B,A,A,A
3 C,D,C
Give the number of duplicate characters, eg: for 1 there are 2 A's and 2 B's, so the result is 2
For 2 A is repeated 4 times so the result is 3
For 3, C is repeated twice so the result is 1
My suggestion was to use a CLRSQL function to calculate it
public class Gen {
public static void main(String[] args) {
Integer i1 = new Integer(1);
Integer i2 = new Integer(1);
System.out.println(i1 != i2);
System.out.println(i1 <= i2);
System.out.println(i1 >= i2);
}
}WHY THE OUTPUT IS TRUE IN ALL CASES?
Find the largest sequence in a array which sums to zero
Provided a number dictionary and a number, x , which is formed from the number dictionary. Find the rank of the number x? Rank is defined as the position of the number x when all the number formed from the dictionary are sorted.
Example
Input :{4,1,5}
X : 451
Output : 4
(145,154,415,451,514,541). 451 comes at 4th position
Write a function to return a path from a given node of a Binary tree to the node on its right.
Each node contains a left pointer, a right pointer and a parent pointer
The root node is not provided, the tree is not balanced, the tree is not a Binary search tree
Finding the root node and running BFS from there is not an acceptable solution. You have 30 minutes to give syntactically correct code
I was unable to complete this question and was rejected without further interviews. Perhaps I did something to offend the interviewer, this was for an entry level SDE position
Design an algorithm for a thermometer that shows the Maximum and minimum temperature in the last 24 hours. The current temperature can be read in 5 second intervals.
The interviewer was looking for an algorithm that is space efficient as there will be limited memory on the device. .
Given as follows:
Given a matrix of size N*N and a starting point "s" in the matrix which represents a color.
Find the area of the shape represented by the color of the starting point "s".
Note 1: A shape can be anything as long as it is connected, e.g. a square, a circle, a doughnut or a line.
Note 2: It is only a shape if they are connected from the starting point.
Note 3: Connected means, adjacent and the same color.
E.g.
zero based index.
Starting point = top left "R" [3][2], color = R, area = 10
000000000
000000000
000000000
00RRRR000
00R00R000
00RRRR000
000000000
000000000
000000000Update: OK as requested further clarifications, a cell is only a single color, it is a matrix and contains
a single value stating the color of the cell. Think of each cell as a pixel and each pixel represents a length of 1.
The shape above has an area of 10, because that it is not a regular square but has two holes in the middle, if you do it mathematically:
(3*4) - (1*2) = 10 or simply by visually counting the R squares.
You are not trying to create shapes, you are using the starting point "s" to find the complete shape (traverse the matrix until you have found all connected pixels) and calculate the area.
If you need more clarification I can try but I think that should clarify.
State your Time and Space complexity of your algorithm.
Consider also this:
0000000000000
0000000000000
0000000000000
0000000000000
0000000000000
00RRRR0000000
00R00R000RR00
00RRRR000RR00
0000000000000
0000000000000
0000000000000
0000000000000
0000000000000
zero based index.
Starting point s = top-left "R" [5][2], area = 10.In the above case, the other shape, same color is not connected to the shape specified by the starting point, hence is not part of the area calculation.
Apologies for the formatting.
Given a mathematical expression, remove the redundant brackets from the expression.
e.g. input: (a + (b*c)) * (d * ( f * j) )
output should be: (a + b * c) *d * f * JWrite a Programme for the Mine Sweeper Game in Java. Not necessary it should have any UI. this question was asked in Thoughtworks,Pune
How to delete two rows from the table in database ?
Note: Delete only first two rows from the Database.
<table style="width:300px" border="2px">
<tr>
<th>USERNAME</th>
<th>LOCATION</th>
</tr>
<tr>
<td>zac</td>
<td>california</td>
</tr>
<tr>
<td>zac</td>
<td>california</td>
</tr>
<tr>
<td>zac</td>
<td>california</td>
</tr>
<tr>
<td>zac</td>
<td>california</td>
</tr>
</table>
Implement LRU cache of size 10 which can store Key, Value pair. (get(key) & put(key,value) methods)
- If we try to add 11th element, the least recently used element should get removed.
- If key already present, overwrite it and mark it as most recently used.
You are given an array of N elements. Each element in the range Min of int to Max of Int. You need to find the length of longest sequence in this array such that difference of largest and smallest element of that sequence is 1. The sequence need not be sequential.
For e.g. array[]={6,10,6,7,8,9,0}
seq {6,10} = diff is 4 len 2
seq { 10,7,8} diff is 3 len 3
seq { 7,8,9} diff 2 len 3
seq {6,6,7} diff is 1 len 3
In this example the program should return 3 .
Complexity N*longN
You have a set of pairs of characters that gives a partial ordering between the characters. Each pair (a, b) means that a should be before b. Write a program that displays a sequence of characters that keeps the partial ordering (topological sorting).
public class LogEntry {
public final long startTime; // start time of a job in millisec granularity
public final long endTime; // end time of a job in millisec granularity.
public final long ram; // the amount of ram the job occupies.
public final long jobId;
... constructor ...
}
running total of RAM
|
| 3GB
| -----
| 2GB
| ------
| 1GB -----------
|----- -----------
|
|____________________________________________________time
Find the peakRAM when the input is a collection of LogEntry objects
Given a string array ex: [1, 2, 3], find the permutation in best time.
Given 4 bottles out of which one is of less weight. Find out the defective one by weighing only once.
Given MxN matrix which contains 1s and 0s, find the largest sub matrix which contains most number of 1s. condition is that each row in the sub matrix must contain at-least one 1.
Flood fill algorithm. He also asked me what else I would do before checking the code to repository?
A non-empty zero-indexed array A consisting of N integers is given. The leader of this array is the value that occurs in more than half of the elements of A.
Write a function:
int arrLeader(int A[], int N);
int arrLeader(NSMutableArray *A);
int arrLeader(const vector<int> &A);
class Solution { int arrLeader(int[] A); }
class Solution { public int arrLeader(int[] A); }
function arrLeader(A);
function arrLeader(A)
function arrLeader($A);
function arrLeader(A : array of longint; N : longint) : longint;
def arrLeader(A)
sub arrLeader { my (@A)=@_; ... }
def arrLeader(a)
Private Function arrLeader ( A As Integer() ) as Integer
that, given a non-empty zero-indexed array A consisting of N integers, returns the leader of array A. The function should return -1 if array A does not contain a leader.
Assume that:
l N is an integer within the range [1..1,000,000];
l each element of array A is an integer within the range [0..2,147,483,647].
For example, given array A consisting of ten elements such that:
A[0] = 4 A[1] = 2 A[2] = 2 A[3] = 3 A[4] = 2 A[5] = 4 A[6] = 2 A[7] = 2 A[8] = 6 A[9] = 4
the function should return -1, because the value that occurs most frequently in the array, 2, occurs 5 times, and 5 is not more than half of 10.
Given array A consisting of five elements such that:
A[0] = 100 A[1] = 1 A[2] = 1 A[3] = 50 A[4] = 1
the function should return 1.
Complexity:
l expected worst-case time complexity is O(N);
l expected worst-case space complexity is O(1), beyond input storage (not counting the storage required for input arguments).
Elements of input arrays can be modified.
// you can also use includes for example:
// #include <algorithm>
int arrLeader ( const vector<int> &A ) {
// write your code here
}
Implement multiple producer and multiple consumer problem in java.
Write a binary search function in C that will work for any datatype. You cannot accept the datatype in the function arguments.
give an algorithm for finding duplicate parenthesis in a expression.
example :
(( a + b ) + (( c + d )))give an algorithm for finding duplicate parenthesis in a expression.
{{ (( a + b ) * (( c + d ))) }}
Find the median of two given sorted array. Give the solution with complexity < O(n).
For a given binary search tree, replace each node with sum of all node which are greater then of equal to current node.
write a program to generate random numbers without using the in-built functions?
He asked me to print root to leaf path WITHOUT using recursion . I got stuck at it and used too much space according to him .
I constructed a visited array , path array and a stack .
Is there any other optimal algorithm ?
a[] is an array containing elements of a BST .
2D array is given where arr[i][j] gives the root of the tree formed by taking elements from index i to j from a[] . construct the BST .
Given pattern P (say aba) search for the pattern if the input is a stream of characters.
1. You cant store the stream of chars. not even till Length(P)
2. You have access to only one char of stream at a time.
I gave KMP algo which was okay for him, but he mentioned you could have used some better DS..
I am wondering which DS can be used to store pattern..
Trie ???
You need to consider cases for stream like aababa
there are 2 occurences
/* This class will be given a list of words (such as might be tokenized
* from a paragraph of text), and will provide a method that takes two
* words and returns the shortest distance (in words) between those two
* words in the provided text.
* Example:
* WordDistanceFinder finder = new WordDistanceFinder(Arrays.asList("the", "quick", "brown", "fox", "quick"));
* assert(finder.distance("fox","the") == 3);
* assert(finder.distance("quick", "fox") == 1);
* /root, directory, 128, admin, NONE
users, directory, 512, admin, root
santana, directory, 1024, santana, users
santana.jpg, photo, 128000, santana, santana
Project.doc, document, 256000, santana, santana
Incredibles.mpg, movie, 4123456123, santana, santana
marcus, directory, 128, marcus, users
Resume.doc, document, 256000, marcus, marcus
This contains information about files stored in a file system. Each line corresponds to one file, and the fields are separated by commas. The first field contains the filename, the second contains the file type, the third field is the size of the file in bytes, the fourth field is the username of the owner of the file, and the last field is the name of the parent directory of this file (i.e. the name of the directory in which this file is located.) Note: the special parent directory name NONE indicates that this file is the root directory of the filesystem. Also, for the purposes of this program, assume that all file/directory names are unique in the system.
write a Java program which reads data in this format from a file, parses it, and figures out the total size of storage consumed by each directory in this system. The size of storage consumed by any directory is defined as the sum of the size of this directory, sizes of all the files in this directory and the total storage sizes consumed by all the directories in this directory. Your program should write the name of each directory, and the total storage consumed by it. The output should have one directory per line, and the format should be dirname: size.
Output should be:
santana: 4123841147
marcus: 256128
root: 4124097915
users: 4124097787
Provide the best algorithm and java program.
Given a balanced BST, how would you return the nth smallest element in logn time .
public interface FirstCommonAncestor {
/**
* Given two nodes of a tree,
* method should return the deepest common ancestor of those nodes.
*
* A
* / \
* B C
* / \ \
* D E M
* / \
* G F
*
* commonAncestor(D, F) = B
* commonAncestor(C, G) = A
*/
public Node commonAncestor(Node nodeOne, Node nodeTwo)
{
}
}
class Node {
final Node parent;
final Node left;
final Node right;
public Node(Node parent, Node left, Node right, data) {
this.parent = parent;
this.left = left;
this.right = right;
this.data = data
}
boolean isRoot() {
return parent == null;
}
}
If in a relation there are multiple duplicate rows . Your task is to delete one duplicate row.
a1 a2
1 3
1 3
2 4
3 5
3 5
3 5
after deletion
a1 a2
1 3
2 4
3 5
3 5
3
Id Key Value
-- --- -----
1 name hulk
2 age 22
3 name ironman
4 age 35
Write an efficient SQL Query to fetch the id of all users whose name starts with h and having age between 22 and 35.
Given two tables
1. Candidate having: Id , Name
2. Vote: Id, CandidateId
Give query to give the name of the winning candidate
Write a test plan for vending machine
What happens when you type in shell
list=$(ls)Interviewer expected the list of system-calls made, file-descriptors involved etc.
Coding Round Assignment
------------------------------------
MERCHANT'S GUIDE TO THE GALAXY
You decided to give up on earth after the latest financial collapse left 99.99% of the earth's population with 0.01% of the wealth. Luckily, with the scant sum of money that is left in your account, you are able to afford to rent a spaceship, leave earth, and fly all over the galaxy to sell common metals and dirt (which apparently is worth a lot).Buying and selling over the galaxy requires you to convert numbers and units, and you decided to write a program to help you.The numbers used for intergalactic transactions follows similar convention to the roman numerals and you have painstakingly collected the appropriate translation between them.Roman numerals are based on seven symbols:
Symbol Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1,000
Numbers are formed by combining symbols together and adding the values. For example, MMVI is 1000 + 1000 + 5 + 1 = 2006. Generally, symbols are placed in order of value, starting with the largest values. When smaller values precede larger values, the smaller values are subtracted from the larger values, and the result is added to the total. For example MCMXLIV = 1000 + (1000 − 100) + (50 − 10) + (5 − 1) = 1944.
The symbols "I", "X", "C", and "M" can be repeated three times in succession, but no more. (They may appear four times if the third and fourth are separated by a smaller value, such as XXXIX.) "D", "L", and "V" can never be repeated.
"I" can be subtracted from "V" and "X" only. "X" can be subtracted from "L" and "C" only. "C" can be subtracted from "D" and "M" only. "V", "L", and "D" can never be subtracted.
Only one small-value symbol may be subtracted from any large-value symbol.
A number written in Arabic numerals can be broken into digits. For example, 1903 is composed of 1, 9, 0, and 3. To write the Roman numeral, each of the non-zero digits should be treated separately. In the above example, 1,000 = M, 900 = CM, and 3 = III. Therefore, 1903 = MCMIII.
-- Source: Wikipedia (http://en.wikipedia.org/wiki/Roman_numerals)Input to your program consists of lines of text detailing your notes on the conversion between intergalactic units and roman numerals. You are expected to handle invalid queries appropriately.
Test input:
-------------
glob is I
prok is V
pish is X
tegj is L
glob glob Silver is 34 Credits
glob prok Gold is 57800 Credits
pish pish Iron is 3910 Credits
how much is pish tegj glob glob ?
how many Credits is glob prok Silver ?
how many Credits is glob prok Gold ?
how many Credits is glob prok Iron ?
how much wood could a woodchuck chuck if a woodchuck could chuck wood ?
Test Output:
---------------
pish tegj glob glob is 42
glob prok Silver is 68 Credits
glob prok Gold is 57800 Credits
glob prok Iron is 782 Credits
I have no idea what you are talking about
Design a mobile app which based on the current location suggests Interesting places to the user. We already have a set of interesting places stored. The focus is on getting the nearby places say in radius of 100 Miles from current location quickly.
The interviewer is mainly interested on how to store the interesting locations in a DB.
write a program to give an array such that:
1. the data value is from 1 to n
2. the length of it is 2*n
3. the two elements with same value keep the same number distance.
for example, when n = 3, the length of array is 6, the array should be like: 2, 3, 1, 2, 1, 3. there are two elements between "2" pair, and three elements between "3" pair and one element between "1" pair
The question was:
What are general guidelines you follow while creating new classes in C++
My answer:
1. Keep variables pvt (use setter and getter methods)
2. Use reference counting to do mem management, he asked me to use shared_ptr within the class
I have two arrays A and B(each containing 8 bit integers). Find the common elements between them.
The questions started out as a general discussion with the most inefficient method. Then the interviewer asked me to improve the solution (to give a NlogN and finally a linear time solution)
An extension of Dijkstra's algorithm:
In a graph each vertex represents a city.
And each edge defines the connectivity between two vertices.
Each edge has two more information
1) the distance between the two vertices
2) A Boolean flag indicating if the destination is uphill or downhill to the source.
One constraint: you can change the path from uphill to downhill or downhill to uphill only once.
E.g: initially if you are going up the hill and at some point choosed to go down the hill, you can not change to take a path which is uphill again..
Similarly you are going down the hill and at some point choosed to go up the hill, you can not change to take a path which is down hill again..
O/P: find the shortest path between source to destination.
Interview gave towers of Honai with 4 pegs namely: source, helper1, helper2, destination.
What are the minimum number of steps to move N number of discs from source to destination.
he was looking for a recursive function which defines the number of moves required for N and the minimum value for that function.
Given a circular linked list with each node either r,g,y or b. number of nodes of each color are same. Arrange the nodes in a specified order. Eg. if list is like "rrrgggyyybbb" and order is "rgyb" then after rearrangement it should be "rgybrgybrgybrgyb". Just a bit more explanation...the question was given in form of students stading in a circular fashion and color denotes the club they are in. Hence adding new node or list is not possible.
You are given a set of nodes, for e.g. 2, 3, 1, 4. Each of them is connected to all of others. There is no cycle, A node can send its value to other node.The receiver node can either overright its value with the new received value, or discard this new value or add this value to its existing value. You need to update each node to sum of all nodes. So for eg. 1, 2,3 4 the output shuold be 10, 10, 10, 10 in minimum no of time unit. One time unit is defined as time taken in one operation. This needs to be done in less then 2n operations.
I have been asked this question in written test. which pattern to use..
Using Java create a simulation of a car park. The
program will record vehicles entering and exiting the car
park, as well as the total balance of parking fees paid.
Cars can park in the car park for $2 per hour.
Trucks can park in the car park for $3 per hour.
For example a car parked for 2 hours will pay $4
and a truck parked for 2 hours will pay $6.
The program can also be asked for a balance report that
will show how many vehicles have entered and exited,
the number of spaces available and how much money has
been paid so far.
Trucks take up 2 car spaces.
The requirements for the interface:
1. The user records vehicles entering and exiting the
car park.
2. Upon exiting the car park a time in whole hours
spent in the car park is also entered.
3. The user can request a balance report of the car park
at any time.
4. The program can be exited at any time.
5. The program should validate user input.
Provide a production ready solution including source
files, project structure and any testing you have used.
Example #1
--------------------------------------------------
Program: How many spaces does the car park have?
User: 10
User: ENTER CAR
User: ENTER TRUCK
User: REPORT
Program:
Cars Entered: 1
Trucks Entered: 1
Cars Exited: 0
Trucks Exited: 0
Parking Cars: 1
Parking Trucks: 1
Spaces available: 7
Fees paid: $0
User: QUIT
Example #2
--------------------------------------------------
Program: How many spaces does the car park have?
User: 15
User: ENTER CAR
User: ENTER TRUCK
User: EXIT CAR 2
User: REPORT
Program:
Cars Entered: 1
Trucks Entered: 1
Cars Exited: 1
Trucks Exited: 0
Parking Cars: 0
Parking Trucks: 1
Spaces available: 13
Fees paid: $4
User: QUIT
Machine Coding 1 hour
------------------------------
U have an organizational structure, which shows hierarchy of the organization. This hierarchy contains employees E or managers M who has some Employees or Managers reporting to M.
Employee has ( id, name, JobDesc, salary etc).
Design the data structure you would be using to store this hierarchy
problem 1: Given an ID of an employee , print all the employee ID's who are directly reporting or indirectly reporting to the manager.
problem 2: prefix search of employees by String. If employees have nishant and nikhil. If searched by "ni" we need to print all details of both nishant and nikhil.
problem 3(bonus): search should print all emloyee's and their details if a given string is subString of the name of an employee.(Like a phonebook contacts search)
P.S- This was asked to one of my friend in Flipkart.
Given an array of positive numbers, find the maximum sum of a subsequence with the constraint that no 2 numbers in the sequence should be adjacent in the array.
You have to print the sub-sequence also.
Generate all Kaprekar Number (refer Wiki for Kaprekar number's definition) from 1 to 999999.
I gave a brute force approach of generating all number in the range and checking if it is Kaprekar or not.
What approach you will take in migrating your production databases from MySql to Postgre SQL with zero downtime.
i) Difference between HashMap & HashTable
ii) How will you implement your own sorting algorithm in java?
Coin Change Problem
-----------------------------
Given an unlimited supply of coins of denominations C1, C2, ..., CN we wish to make change for a value V. Give an algorithm for producing change with minimum number of coins.
You have to print the denominations selected.
1 2 3
4 5 6
7 8 9
* 0 #
Given a starting number, find all 6-digit numbers possible, numbers can only be dialed horizontally or vertically.
Repetitions not allowed. Number can't start from zero and doesn't include * and #. For example, if last dialed number
is 3, the next one could be 1, 2, 6 or 9.
For a given array with positive and negative element, find sub array with maximum sum. Sub array must have same sequence of element as that of parental array.
Eg: P = {4,6,-3,1,5,9,-2} then S ={4,6,-3,1,5,9} //Correct output.
Construct an array of size 10 such that if a[x] =y then x should be repeated y times in that array. Eg: If a[1] = 2 then 1 should be present in that array 2 times.
Given three strings a, b, c. Write a function to find the smallest subsequence in a, which contains all the characters from b but none from c.
* b and c are mutually exclusive.
Create a Employee Database for an organization. Each employee may or may not have a manager. One employee may have many subordinates. This can grow upto any level.
* Find all the subordinates for a given employee.
* Find the manager details of an employee.
Assumptions:
* Employee contains
ID: int (Unique)
Name: string
Designation: string
Email: string
* One employee can have only one manager.
* All the information is in-memory. No database needed.
You want to create a staff to use in your martial arts training, and it has to meet some specific requirements.
1. You want it to be composed of two smaller staves of equal length so that you can either use it as a single staff or as two smaller ones.
2. You want the full sized staff's center of gravity to be exactly in the middle of the staff.
You have a very, very long branch from which you can cut the pieces for your staff. The mass of the branch varies significantly throughout it, so you use just any two pieces of the same length. Given a description of the mass throughout the branch, determine the longest staff you can make, then return three integers on a single line, the first two indicating the first index of each half-staff, and the third indicating the length of each half-staff.
The input will be given on a single line as a string of digits [1-9], each digit representing the mass of a section of the branch. All sections are the same size and the maximum length of the string is 500. Here is an example:
41111921111119
11119 11119
If the indicated sections are cut from the branch they will satisfy your requirements. They are both the same length, and they can be put together as either 9111111119 or 1111991111, both of which have a center of gravity exactly in the center of the staff.
Center of gravity can be determined by taking a weighted average of the mass of each section of the staff. Given the following distances and masses:
Distance: 12345678
Mass: 22241211
Sum of the mass of each section: 2 + 2 + 2 + 4 + 1 + 2 + 1 + 1 = 15
Weighted sum of the masses:
2*1 + 2*2 + 2*3 + 4*4 + 1*5 + 2*6 + 1*7 + 1*8 = 60
Weighted sum / regular sum = 60 / 15 = 4
This means that the center of mass is in section 4 of the staff. If we wanted to use this staff the center of gravity would need to be (8+1)/2 = 4.5.
Here is an example problem:
131251141231
---- ----
If we take the sections indicated we get 1312 and 1231. By reversing the first one and putting them together we get 21311231
Sum of the mass of each section: 2 + 1 + 3 + 1 + 1 + 2 + 3 + 1 = 14
Weight sum of the masses:
2*1 + 1*2 + 3*3 + 1*4 + 1*5 + 2*6 + 3*7 + 1*8 = 63
Weighted sum / regular sum = 63 / 14 = 4.5
This puts the center of mass exactly in the center of the staff, for a perfectly balanced staff. There isn't a longer staff that can be made from this, so the answer to this problem is
0 8 4
Because the half-staves begin at indices 0 and 8 (in that order) and each is of length 4.
Code for computing a^b and optimize it.
The nargin and nargout command returns the number of input and output respectively for a function.
nargin is particularly useful when the input values are trivial. For example (0, 0) seems to be trivial
input in Q5. Modify the program so that the default value of (a,b) is (0,0) whenever it is not specifed
by the user.
Q5:The following function is supposed to generate an array of Cartesian coordinates for a circle with
radius r and centered at (a; b).
function [x,y] = circle(r,theta)
theta = [0:pi/100:2*pi];
x = r*cos(theta);
y = r*sin(theta);
end
Write a MATLAB function maxmin that returns the maximum and minimum value for an input array
x as well as the indices that correspond to the maximum/minimum.
Write a MATLAB function that takes a matrix A as an input and returns it's diagonal part D,
lower triangular part L and upper triangular part U.
given a string determine which character appears the most and the number of times that character appeared.
The buildings of an office are numbered sequentially. Person A is in building 1 and person B is in building 106. If A crosses 5 offices in a minute and B crosses 10 offices in a minute, at which office number will they both meet?
Find the next number in the series.
-3, 6, -18, 72, - 360
Find the missing number in the series.
3, 8 , 18 , _ , 78
A string 'aBlY' is said to be well ordered because the letters of the string occur one after the other in the alphabet. Write a function where the number of letters in the string are passes as parameter and all such well ordered strings are found.
Let the user enter a decimal number. The range allowed is 0.0001 to 0.9999. Only four decimal places are allowed. The output should be an irreducible fraction.
Eg: If the user enters 0.35, the irreducible fraction will be 7/20.
There are two roommates. Each one prepares a list for grocery store. Make a combined list without any duplicates.
Write a program for a word search. If there is an NxN grid with one letter in each cell. Let the user enter a word and the letters of the word are said to be found in the grid either the letters match vertically, horizontally or diagonally in the grid. If the word is found, print the coordinates of the letters as output.
Which is better HashMap or HashTable? Why?
When do you use HashMap?
void test(final Object o1, final Object o2) {
…
synchronized(o1) { … }
....
synchronized(o2) { … }
}
Does deadlock happens if two threads simultaneously called it as follows:
test(A, B);
test(B, A);
where A and B are instances of some class X.
Do STL containers always create copy of objects when containers are populated (e.g. if you have a vector<A> or a map<int, A>, when we insert elements into vector/map, whether copies of object of class A would be stored inside the vector/map?
How would one design a multi format converter that supports reading data from multiple data sources(web service, local disk, etc.). The data from the sources can be in multiple formats. The reader for each format may be different and how does one serialize this abstract data to multiple formats like image, xml etc. New readers, writers and data sources can be added later during implementation.
As you are on Seattle, tell me how many rain drops pour on earth every year
We have a bag containing numbers 1, 2, 3, …, 100. Each number appears exactly once, so there are 100 numbers. Now one number is randomly picked out of the bag. Find the missing number.
Given an array of non-repeating, non-sorted, positive and negative integers, find 4 numbers in that array which satisfy the following equation: A1 + A2 + A3 = A4
Complete the function to return the value A4. If no such numbers satisfy the given equation, return -1,
In case of multiple possibilities that satisfy the equation, return the largest such value of A4.
Sample Test Case:
Sample Input: {-6,2,4,8}
Sample Output: 4
Explanation: The value 4 can be achieved as follows: 8+2+(-6) = 4
IMPORTANT: You do not need to write full code. Just complete the given function.
/**This class find sequence of elements in an array which satifies a1+a2+a3=a4.
* @author Kishor Kumar Padhan
*
*/
public class EquationInArray {
public static void main(String[] args) {
int[] arr = new int[] {-6,2,4,8};
int[][] arr1 = new int[arr.length*(arr.length-1)][2];
int k=0;
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr.length; j++) {
if(i!=j) {
arr1[k][0] = arr[i];
arr1[k][1] = arr[j];
k++;
}
}
}
int bigMatchedNumber=0;
String bigMatchedEquation="";
int m=0;
while(m<arr1.length) {
for(int n=0;n<arr.length;n++) {
if(arr1[m][0]!=arr1[n][1] && arr1[m][1]!=arr1[n][1]) {
int total = arr1[m][0]+arr1[m][1]+arr1[n][1];
if(doesNumberExists(total,arr)) {
if(total>bigMatchedNumber) {
bigMatchedNumber=total;
bigMatchedEquation = arr1[m][0]+"+"+arr1[m][1]+"+"+arr1[n][1]+"="+total;
}
}
}
}
m++;
}
System.out.println("bigMatchedEquation : " + bigMatchedEquation);
}
private static boolean doesNumberExists(int total, int[] arr) {
boolean matched = false;
for (int i = 0; i < arr.length; i++) {
if(total == arr[i]) {
matched = true;
}
}
return matched;
}
}Find the maximum sum subset in an array with negative integers
find the Maximum product subset with negative and positive integer
Given a string of n characters how would you replace all occurrences of a particular character with some other character- with a time complexity less than O(n)?
Note: W/o using any inbuilt string replace functions of the language.
/**
* Implement a function OneEditApart with the following signature:
* bool OneEditApart(string s1, string s2)
*
* OneEditApart("cat", "dog") = false
* OneEditApart("cat", "cats") = true
* OneEditApart("cat", "cut") = true
* OneEditApart("cat", "cast") = true
* OneEditApart("cat", "at") = true
* OneEditApart("cat", "acts") = false
* Edit is: insertion, removal, replacement
*/
Given the following filename/rules:
johndoe_sdfjkldfj_ldfjlkfdsjfds_dfdjklfdsjs.txt
Rules:
johndoe is a distinct identifier (not a constant)
any following items are tacked on with underscores separating them and each token contains a key value pair. The key is the first character and the value is the remaining characters.
Parse this filename and return a dictionary/hashtable of values, removing any file extensions but also keeping in mind that this filename could end up with incorrect characters or incorrect amounts of characters.
Example input:
johndoe_sdfjkldfj_ldfjlkfdsjfds_dfdjklfdsjs.txt
Example output:
@{ @"NAME" : @"johndoe",
@"s" : @"dfjkldfj",
@"l" : @"dfjlkfdsjfds",
@"d": @"fdjklfdsjs"
};
Followup: How would you handle it if you found multiple tokens with the same key?
Design and code the logic software for an elevator, pretending like the hardware is already there for you with the following APIs:
- OpenDoor()
- GotoFloor()
Given 2 sorted lists that are of even and equal size, output the median. If there is no middle number, return the average of the 2 middle numbers
Given an array of words, write a method that determines whether there are any words in this array that are anagrams of each other.
Sample #1: @[@"bag", @"bat", @"tab"]; // output TRUE
Sample #2: @[@"gab", @"bat", @"laf"]; // output FALSE
An UIView A2 is subclassed from the same parent as an UIView A1.
Given inputs of A1, A2, and an UIView that is in the tree of UIViews of A1 somewhere, return the exact UIView that mirrors this in A2.
Example setup:
A1------------
| |
UIView UIView
|
UIView <-- Given this
A2------------
| |
UIView UIView
|
UIView <-- Find/return this
Given a list of n sorted lists of numbers, write a method that returns one giant list of all the numbers in order.
Example input:
NSArray* input = @[
@[@2, @5, @10],
@[@25, @100, @105],
@[@7, @56, @42],
.......
];
Given the following hashmap for numeric to alpha translation of a telephone keypad:
NSDictionary* dict = @{@2: @[@"A", @"B", @"C"],
@3: @[@"D", @"E", @"F"],
@4: @[@"G", @"H", @"I"],
@5: @[@"J", @"K", @"L"],
@6: @[@"M", @"N", @"O"],
@7: @[@"P", @"Q", @"R", @"S"],
@8: @[@"T", @"U", @"V"],
@9: @[@"W", @"X", @"Y", @"Z"]};
Write a method that takes a phone number as input and returns all possible letter combinations for that phone number.
How would you speed up dynamically generated web content?
Given a spreadsheet program, determine a method to prevent recursive formula calculation
How can we achieve something similar to polymorphism in C language? Polymorphism is an OOPs feature.
Write test cases for a software which accepts inputs as dd/mm/yyyy and gives output as 4 days after the input.
ex-input-07/01/2011..out put should be 11/01/2011.
give boundary values of each test cases..assume dd/mm/yyyy in correct format
implement division without using division operator in log(n) time.
Can we write a collection class in C++ that can store elements of different data types?
8 coins are given where all the coins have equal weight, except one. The odd one may be less weight than the other or it may be heavier than the rest 7 coins. In worst case, how many iterations are needed to find the odd one out?
An array which is a Post order traversal of a Binary Tree. Write a function to check if the Binary Tree formed from the array is a Binary Search Tree.
Eg:
2
1 3
The array given as input would be 1 3 2.
Write a function to say if the tree formed is a Binary Search Tree.
Example 2: 4 is root. 0 is left child of 1 , 1 is left child of 2 and 2 is left child of 4. 5 is right child of 4 and 6 is right child of 5.
4
2 5
1 6
0
0 1 2 6 5 4 is the input array.
Observe the following function declaration and choose the best answer:
int divide ( int a, int b = 2 )
Given a set of integral coordinates, find the minimum area of a rectangle that can be drawn to encompass all the points. The sides of such a rectangle have to be parallel to the two axes. Return the area of the rectangle.
Sample Test Case
Sample Input:
4
1 1
1 4
2 2
5 3
Sample Output: 12
Explanation: The points are (1,1) , (1,4) , (2,2) and (5,3) and the area of the rectangle that encompasses all the points is 12.
Given an array of integers, sort the array into a wave like array, namely
a1 >= a2 <= a3 >= a4 <= a5.....
Give this input: Sea!tle is a nice place. Work Hard! have Fun, make HIStory!
display this output using any C or vb script:
Seattle is a nice place.
Work hard.
Have fun.
Make history.
Given three strings str1, str2 and str3; complete the function to find the smallest subsequence in str1 which contains all the characters in str2 (in any order) and not those in str3.
Sample Test Case:
Sample Input:
str1: spqrstrupvqw
str2: sprt
str3: q
Sample Output: strup
Explanation: In the given string str1, the smallest subsequence that contains the characters in str2 ( 's' , 'p' , 'r' , 't' ) and does not contain the character in str3 ( 'q' ) is 'strup'.
Design a web-site like Paypal.
The interviewer was interested in the
i) Major components & the way they will interact.
ii) Various way of scaling the web-site to support many users
iii) Handling the failure cases like when the DB goes down, etc.
Given a binary matrix of 0 and 1. Find the longest sequence of 1's either row wise or column wise.
For example
0 0 0 0 0 0
0 1 1 1 0 0
0 0 0 1 0 0
It should return 1 1 1
Can anyone tell me that from where i can get/download java code on Ray Casting Algorithms or Point in Polygon algorithms? or any library is avaiable.
Input will be a matrix consiting of only 1's n 0's.
The 1's represent the lines and 0's its absence.
For eg a matrix 6X7 is shown
0 0 0 1 1 1 1
0 1 1 1 0 1 1
0 1 0 1 0 1 1
0 1 0 1 0 1 1
0 1 1 1 0 1 1
0 0 0 1 1 1 1
In the above matrix, the sequence of 1’s represents the lines. These eight lines constitute three
rectangles.
Conditons :
1. The rectangles will always enclose some 0’s. e.g. last two vertical lines does not constitute a
rectangle.
2. A rectangle can contain multiple rectangles
Output : should be no. of rectangles formed in the matrix(intersecting rectangles are also counted).
Leetcode: Jump Game.
Given an array of non-negative integers, you are initially positioned at the first index of the array.
Each element in the array represents your maximum jump length at that position.
Determine if you are able to reach the last index.
Given a string, reverse the word, but keep the comma, number and space.
Given a matrix, there are two 1s and many 0s. Find a path from the first 1 to the second 1.
Find Top k most frequent elements
Find Top k biggest numbers
Determine minimum sequence of adjacent values in the input parameter array that is greater than input parameter sum.
Eg
Array 2,1,1,4,3,6. and Sum is 8
Answer is 2, because 3,6 is minimum sequence greater than 8.
You are given a matrix where some pixels are white and some are black. Basically there are different disjoint images in the matrix.
a) Expand/Shrink the images
b) Count the no of images
c) Color the images
d) Rotate the images
Given three points in a 2D plane with their (x, y) coordinates say if the origin lies inside the triangle formed by the three points.
Disconnect two nodes in a graph by removing minimum number of edges.
Given a matrix pattern containing only 'plus' & 'dots',search no of times that pattern is present in a very large file which has a very large matrix which contains 'plus' and 'dots'.
I/P: An array of Integers: which will be used to construct a binary search tree in the order they appear.
o/p: all permutations of the input elements which will result in the same Binary Search tree as the one formed with the input array.
Eg:
I/P: 4, 3, 1, 2, 6, 5, 7
o/p:4 , 6, 3, 7, 5, 1, 2
4, 3, 2, 1, 6, 5, 7
and soo on.
design e commerce web site like amazon....
given data about students who had taken some subjects.
I had to make a data structure such that if I query for no of students in a subject or no of subjects a student has taken, the complexity should be less.
Given an nxn screen, Each pixel is represented by intensity values. Given a specific pixel as an input, find the no. of pixels of the same colour which can reached from this pixel. Assume any suitable data structure for a screen.
Objective: Write a function to find all the combinations of three numbers that sum to zero
Sample input:
[2, 3, 1, -2, -1, 0, 2, -3, 0]
Sample output:
2, -2, 0
1, -1, 0
3, -2, -1
3, 0, -3
3, 0, -3
write a function that has an int as input and return the equivalent String as an output
12 -> 'twelve'
4345 -> 'four thousand three hundred and forty-five'
7654567643 -> 'seven billion six hundred and fifty-four million five hundred and sixty-seven thousand six hundred and forty-three'
3, 5, 7, 9, 11, 13. Which is least like others?
3, 5, 7, 9, 11, 13. Which is least like others?
I was asked this during a recent interview.
Lucky number – a number is a lucky number if it comprises of combination of 4′s and 7′s.
For example , if 32 is the input number, the next nearest lucky number would be 44.
Similarly ,
43 -> 44
45 -> 47
1004 -> 4444
Input number can be of any digits.
Design an algorithm that will take any random number and return its next lucky number
In Byteland they have a very strange monetary system. Each Bytelandian gold coin has an integer number written on it. A coin n can be exchanged in a bank into three coins: n/2, n/3 and n/4. But these numbers are all rounded down (the banks have to make a profit).
You can also sell Bytelandian coins for American dollars. The exchange rate is 1:1. But you can not buy Bytelandian coins. You have one gold coin. What is the maximum amount of American dollars you can get for it?
Input The input will contain several test cases (not more than 10). Each testcase is a single line with a number n, 0 <= n <= 1 000 000 000. It is the number written on your coin.
Output For each test case output a single line, containing the maximum amount of American dollars you can make.
Explanation You can change 12 into 6, 4 and 3, and then change these into $6+$4+$3 = $13. If you try changing the coin 2 into 3 smaller coins, you will get 1, 0 and 0, and later you can get no more than $1 out of them. It is better just to change the 2 coin directly into $2. Pls suggest a better approach.
Here's My code:
import java.util.*;
class Bytelandain
{
Vector v= null;
Scanner sc = null;
public Bytelandain()
{
v = new Vector();
sc = new Scanner(System.in);
int i=1;
String s =null;
while (i<=10 )
{
s = sc.nextLine();
if( s.equals("") )
break;
int temp = Integer.parseInt(s);
v.add(temp);
i++;
}
for(i=0;i<v.size();i++)
{
showProfit((Integer)v.get(i));
}
}
public static void main(String args[])
{
Bytelandain by = new Bytelandain();
}
public void showProfit(int num)
{
System.out.println(computeValue(num));
}
public int computeValue(int num)
{
int value = 0;
if(num<=2)
{
return num;
}
value = getProfit(num,value);
if(num >= value)
{
return num;
}
return value;
}
public int getProfit(int num,int value)
{
int sum;
sum = value;
sum = sum+ computeValue(num/2)+computeValue(num/3)+computeValue(num/4);
return sum;
}
}Given a sequence of n random numbers: suppose: 1,5,7,3,...
and n-1 symbols of <,> in the given fashion:
_<_>_>_>.....
the task is to fill the blank best possible time complexity. (I solved upto O(nlogn))
Q1. Given array a[]={'a','n','u','b','h','a','v'}
You have to generate a[]={'v','a','h','b','u','n','a'} in the same array with space complexity O(1). You may use just one bit extra.
Q2. perform the same operation with the same constraints for
array a[]={'m','y',' ','n','a','m','e',' ','i','s',' ','a','n','u','b','h','a','v'}
Q3 Perform the same operation with same contraints to arrange the words in alphabetic order, ie the output array should be:
a[]={'a','n','u','b','h','a','v',' ','i','s',' ','m','y',' ','n','a','m','e'}
The input is a sequence x1,x2,...,xn of integers in an arbitrary order, and another sequence
a1,a2,..,an of distinct integers from 1 to n (namely a1,a2,...,an is a permutation of
1, 2,..., n). Both sequences are given as arrays. Design an 0(n logn) algorithm to order
the first sequence according to the order imposed by the permutation. In other words, for
each i, Xi should appear in the position given in ai. For example, if x = 17, 5, 1,9, and a =
3, 2, 4, 1, then the outcome should be x = 9, 5, 17, 1. The algorithm should be in-place, so
you cannot use an additional array.
Given a random generator rand(5) which generates numbers between 0 to 4. How do u generate numbers between 0 to 6, I.e. Implement rand(7).
Car parking problem. An array given represents actual order of cars need to be parked. Like for example order is 4,6,5,1,7,3,2,empty. If cars are parked in some order like empty,1,2,3,7,6,4,2. Some person needs to get them into correct order, list out all instructions to the person to get in correct order with least number of swaps.
Given a list of tuples representing intervals, return the range these intervals
covered.
e.g:
[(1,3), (2,5),(8,9)] should return 5
Consider a game of chess where there is a special queen which has the powers of a Queen as well as a Knight. For eg. in the following arrangement, squares marked with 'x' are in the attackzone of the special queen and the ones marked '0' are in the safe zone:
x O O x O O x
O x x x x x O
O x x x x x O
x x x Q x x x
O x x x x x O
O x x x x x O
x O O x O O x
Your task is to determine the number of ways in which you can place M such queens on a MxM chess board so that they are in equilibrium i.e. they are placed such that no queen is in the attack zone of the other.
Assume M<15. If you need coordinates to identify each square, you can assume that the top-left square is marked (1,1) and the bottom right square is marked (M,M).
Find x^y where y can be float. Any good algorithm for that?
You type www.yahoo.com on the browser . But it will display
nothing or blank page.what is the problem?How will you resolve/
given a N x N matrix find the no. of times a word is present in that matrix. constraints you can move in 3 directions from one cell 1. forward , 2. down 3. diagonal . Find all teh occurance of all the word
forward means right (x+1,y)
down mean (x,y+1)
diagonal means (x+1,y+1)
it can be done with BFS. {search the no. of occurance of a given word example "sachin" in the whole NxN matrix}
w | s | r | t | g | g|
a | a | c | h | i | n |
k | c | h | u | j | j |
o | h | i | n | y | q |
in this sachin can be found out 3 times.
I was asked this an interview at amazon and could not complete this. can I get some help?
am just totally blocked on this. I know what to do but I am having difficulty manipulating the tree. please help.
I am trying to delete and node from an BST. I am able to lookup and find the parent and store it an tree.
package com.test.binarytree;
public class BinaryTreeDelete {
private Node root;
//create null binary tree
public BinaryTreeDelete(){
root = null;
}
//delete
public void delete(int target){
root = delete(root, target);
}
public Node delete(Node node, int target){
NodeWithParent temp = lookupFindParent(root, null, target);
if( node == null){
return null;
}
else{
if( node.left == null || node.right == null) //leaf node
{
//WHAT DO I DO HERE
//temp.parent.left = null;
//temp.parent.right = null;
//return null;
}
if( node.left != null && node.right == null ) //one child only on left
{
//WHAT DO I DO HERE
}
if( node.right != null && node.left == null ) //one child only on right
{
//WHAT DO I DO HERE
}
if( node.left != null && node.right != null ) //two children
{
//WHAT DO I DO HERE
}
}
return null;
}
private NodeWithParent lookupFindParent(Node node, Node parentNode, int target){
if( node == null ){
return null;
}
if( node.data == target){
return new NodeWithParent(node, parentNode);
}
else if( node.data > target ){
parentNode = node;
return lookupFindParent(node.left, parentNode, target);
}
else{
parentNode = node;
return lookupFindParent(node.right, parentNode, target);
}
}
//insert
public void insert(int data){
root = insert(root, data);
}
public Node insert (Node node, int data){
if(node == null){
node = new Node(data);
}
else{
if( data <= node.data ){
node.left = insert(node.left, data);
}
else{
node.right = insert(node.right, data);
}
}
return node;
}
//print tree
public void printTree(){
printTree(root);
System.out.println();
}
//print tree
private void printTree(Node node) {
if (node == null) return;
// left, node itself, right
printTree(node.left);
System.out.print(node.data + " ");
printTree(node.right);
}
//node class
public static class Node{
Node left;
Node right;
int data;
Node(int newNode){
data = newNode;
left = null;
right = null;
}
}
//node class
public static class NodeWithParent{
Node current;
Node parent;
NodeWithParent(Node current, Node parent){
this.current = current;
this.parent = parent;
}
}
public static void main(String[] args) {
BinaryTreeDelete bt = new BinaryTreeDelete();
//insert with inserts - tree increases on right if inserted in order
bt = new BinaryTreeDelete();
bt.insert(5);
bt.insert(3);
bt.insert(7);
bt.insert(1);
bt.insert(4);
bt.insert(6);
bt.insert(9);
bt.printTree();
//bt.delete(3);
//bt.delete(4);
//bt.delete(6);
bt.delete(9);
//bt.delete(5);
bt.printTree();
}
}
C++ Program that uses Linked List to display an Address Book (Name, Address, and Phone number)
Note:phone numbers format: (xxx)-xxx-xxxx
Address should ..street...City...State...Zip
Given a list of interval , find the maximum overlapping interval. For ex if input is (0,5) (2,9) (8,10) (6,9) then ans is 2,9 as its overlap are 3.
Given a tree T of nodes such that each node contains a number. A set of nodes is a Largest independent set of T (i.e. there can be no common edge between the elements). Use dynamic programming to solve this.
No recursion only loops and table must be used, you can recurse through the tree to fill some initial values in the table
Write an efficient algorithm to the situation.There are 8 cubicles in a room. In each cubicle, there are 8 computers.
There are a total of 60 members.
Constraint#1 - A team can contain a minimum of 2 members and a maximum of 6 members.
Constraint#2 - In every cubicle, not more than 1 computer can be unallocated.
Constraint#3 - All team members of a team must be in the same cubicle.
Write an algorithm for maintaining the situation.There are 8 cubicles in a room. In each cubicle, there are 8 computers.
There are a total of 60 members.
Constraint#1 - A team can contain a minimum of 2 members and a maximum of 6 members.
Constraint#2 - In every cubicle, not more than 1 computer can be unallocated.
Constraint#3 - All team members of a team must be in the same cubicle.
You have a complete graph with N vertices. You know that all edges have a cost of A and you are given a set of K edges whose cost is B. Find the shortest (cheapest) path from node 0 to node N - 1.
0 < N, K < 500k
1 < A, B < 500k
There are at most eight servers in a data center. Each server has got a capacity/memory limit. There can be at most 8 tasks that need to be scheduled on those servers. Each task requires certain capacity/memory to run, and each server can handle multiple tasks as long as the capacity limit is not hit. Write a program to see if all of the given tasks can be scheduled or not on the servers?
Ex:
Servers capacity limits: 8, 16, 8, 32
Tasks capacity needs: 18, 4, 8, 4, 6, 6, 8, 8
For this example, the program should say 'true'.
Ex2:
Server capacity limits: 1, 3
Task capacity needs: 4
For this example, program should return false.
Got some idea that this needs to be solved using dynamic programming concept, but could not figure out exact solution.
I attended a telephonic round for appstore testing and successfully cleared this round. Following was the 2nd question(apart from tell me abt yourself,etc):
Give all testcases for creating and renaming a folder in a parent directory, say c drive
I attended a telephonic round for appstore testing and successfully cleared this round. Following was the First question(apart from tell me abt yourself,etc):
Give me all possible test cases for gmail registration page.
give me the code for :
Given a string say "I am a human being" the output should reverse all letters of each word but not the whole string as such.
Eg: O/p should be "I ma a namuh gnieb"
I somewhat wrote the code, but i was asked what if there are extra spaces etc.
(i am able to write the code sitting at my desktop at one short but there front of interviewer i am struggling. Need to build up my confidence)
let me know the best and optimised way of writing this code.
Also i suggest people to aviod using inbuilt functions as much as possible
My Answer is as below in perl
#i want the reverse of the letters of all words in a string
#eg Input is "I am a human being" then o/p shud be "I ma a namuh gnieb"
$str="I am a human being";
@arr=split(' ',$str);
print @arr;
for($i=@arr-1;$i>=0;$i--)
{
$_=@arr[$i];
####intead of above for loop if we use foreach(@arr) then it will reverse the whole string
@word=split('',$_);
{
foreach $n (@word)
{
unshift(@final,$n);
}
}
}
print "\n @final \n";give me a code to find all anagrams or combnations of a given work.
Say if the word given was "hello"
then
hel
he
hell
leho
lleho
and so on
Given an array say [0,1,2,3,5,6,7,11,12,14,20]
given a number say 5.
Now find the sum of elements which sum to 5
eg:2+3=5, 0+5=5 etc.
I guess the interviewer wanted all possible combinations eg 0+2+3=5, etc
A very interesting Question to be done in C or C++ as platform:
Given two input files.
Input file1.csv
Each line in the file describes a websites.
The first field is unique identifier for the site, the second field is the minimum amount in cents, the third field is a string that is the site’s URL:
2181, 320, abc.com
3288, 450, pqr.com
9662, 567, xyz.com
2675, 721, lmn.com
6434, 500, rst.com
8123, 5000, jjj.com
Input file2.csv
Each line in the file describes an ad. The first field is a 32bit unsigned integer which is the unique identifier for the ad , the second field which is the maximum amount in cents the ad is willing to pay to show on a site, the third field specifies the number of sites the ad wants to display on, followed by the site_ids of the sites.
9822, 450, 3, 2181, 9662, 66434
3421, 897, 3, 2675, 9662, 3288
8961, 342, 1, 9662
7623, 2000, 3, 2181, 2675, 9662
all integr fields are 32bit unsigned integer
In the above example, ad 9822 is willing to play on 3 sites(abc.com, xyz.com and rst.com) and pay a maximum amount of 450 cents. WAP that decides the appropriate ad by applying the following rules
1. An ad can be shown on this site only if the site is in the list of sites that the ad is interested in.
if no ad id found for a ite, then no ad is returned
2. The ad that is returned is chosen an auction thats is called second price auction. For ads to qualify for the second price auction,
auction for a site their bid_price should be greater than or equal to the reserve_price of the
site. The winner of the auction is the ad that has the maximum bid_price among these ads, and this
winning ad pays the second highest ad’s bid_price. For instance, if two ads with bid_price 500
and 600 are competing for a site that has a reserve_price of 400, then the ad that bid 600 wins,
but pays 500 (the second highest ad’s bid price).
3. In case of a tie between two or more ads, the ad with the lower ad_id wins and pays it’s
bid_price. In case, the auction has only one ad that qualifies, then that ad wins and pays
reserve_price of that site.
4. In case there are no ads that qualify for the auction for a site either because no ad expresses interest
in playing on that site or because none of the ads have bid_price greater than or equal to
reserve_price of that site then no ad is returned.
Your server should accept input file path,first.csv and the second.csv as
arguments and wait for input. The input is the site_id and the adserver should return the ad_id of the ad that wins the second price auction and price the ad pays for the display. An input of 1 ends the program. example:
$ ./adserver sites.csv ads.csv
2675
7623 897
3288
3421 450
6434
0 0
9999
0 0
8123
0 0
1
$
DIRECTIONS:
1. The code should compile at least on
http://www.compileonline.com/compile_cpp_online.php
2. Please note that will test your program on larger input files with 20K+ sites and
20K+ ads.
3. You have 1.5 hour to solve the problem, test and submit your solution. Your goal is to provide a working solution at least. You may submit additional code later if you think you can make it work better or faster.
For starters If I were to do this in Java:
Algo:
Step1: I/O
Store both the File Paths from STD IN
Take the SITE_ID as Input Then
Step 2: Pre Processing
Site_Map:
Create a Dictionary/HashMap of All the Site_ID and their Price
Ad_Map:
Create a Dictionary/HashMap of All the Ad_ID and the Ammount they Have
Site_to_Ad Map:
Create a Dictionary/HashMap of All the Site_ID and the Ad_IDs Interested to be on them.
Step 3: Auction Method
Iterate through the Site_to_Ad Map.
Fetch the Amount for Each ad_id from the Ad_Map
Compare it against the min price and if greater store it in a variable along with the ID. Fetch the Next ID and IF it is Higher, Replace and put this value in the variable. If there is a draw, compare the two ap_ids and store the one that has min ad_id value.
If min bid is not reached or if there are no ad_id values for that site, return no ad.
Add Constraints to the Auction block.
I believe in c++ we would use Dictionaries to achive this as we have HashMap in Java, can someone help m with the syntax.
Consider the array 3 5 7 6 3.
Return the pair of indices that forms the slice where the difference between the maximum and minimum in the slice <= 2.
Output:
(0,0) (1,1) (2,2) (3,3) (4,4) (5,5)
(0,1) (1,2) (1,3) (2,3)
Example slices: 3 5, 5 7, 1 3, 2 3.
The following link
https://codility.com/media/train/solution-count-bounded-slices.pdf
has O ( n ) solution. But couldn't understand the O (n ) solution. Could some one explain with an example?
Given a sorted array, with find function that finds value in array in O(1). Suppose I rotate the sorted array at some pivot unknown to you beforehand. So for instance, 1 2 3 4 5 might become 3 4 5 1 2. Write new find function wiht uses of the older find to find element in the rotated array in O(1) time.
Develop a Dictionary supporting one implementation.
This implementation can only use List interface.
A Dictionary maps a String term to a String definition; duplicate terms are allowed but
must be in stored/displayed in alphabetical order.
Dictionary must have printTermsInLexOrder(), among other methods. This method displays the term -> definition; this mapping is displayed in alphabetical order.
List interface only -> you can't use other Collections classes.
Given a sorted array with duplicates and a number, find the range in the
form of (startIndex, endIndex) of that number. For example,
find_range({0 2 3 3 3 10 10}, 3) should return (2,4).
find_range({0 2 3 3 3 10 10}, 6) should return (-1,-1).
The array and the number of duplicates can be large.
get this code working with making just one character addition/deletion/replacement:
void Print20Stars()
{
int n=20
for(int i=0;i<n;n--)
{
print('*');
}
}Threre are two interfaces A , B which contains the same method methodC()...and C class implements A&B
which interface method it should be implemented A or B
Create a load balancer supporting three operations in O(1):
void AddServer(Server server)
void RemoveServer(Server server)
Server ReturnRandomServer()
N Queens problem
Write the code to detect when a winning pattern is present in a board.
Given a number N, find the smallest even number E such that E > N and digits in N and E are same.
Print NONE otherwise.
Sample:
Input
N = 34722641
Output
E = 34724126
Input
N = 8234961
Output
E = 8236194 (instead of 8236149)
Java solution
Given two words, determine if the first word, or any anagram of it, appears in consecutive characters of the second word. For instance, tea appears as an anagram in the last three letters of slate, but let does not appear as an anagram in actor even though all the letters of let appear in slate.
Return the anagram of the first word that has appeared in the second word.
Sample Input 1
tea
slate
Sample Output1
ate
Sample Input 2
let
slate
Sample Output2
NONE
java solution
Given a string, complete the given function to recursively remove the adjacent duplicate characters and return the resultant string. If there are no characters left in the resultant string, return "-1" (without quotes).
Sample Test Cases
Sample Input: ABCCBCBA
Output: ACBA
Explanation: (ABCCBCBA --> ABBCBA --> ACBA)
Sample Input: AA
Sample Output: -1
Java solution
How would you debug a Linux program taking too much memory.
There are 2 sets A and B of numbers where numbers are keep coming at high speed. At any given time, you need to find 'A UNION B', 'A INTERSECTION B', 'A - B' and 'B - A'.
How will you store numbers and how will you find these value in real time?
Get numbers that have 90% percentile rank from a collumn in db that contains integers. (their solution is using ntile)
retain vs assign (Objective C)
what is seletector (Objective C)?
which JSON framework is supported by iOS?
What's CoreData (Objective C)?
The ways to store data locally on device (for iOS)?
Round 3 of the interview(in person)
On amazon website, what does the request most recent viewed items API look like?
On server side, design a data structure to cache the most recent viewed item for all clients( consider the size of amazon user)
Round 3 of the interview(in person)
Design a online chess game.
Detail design of the chess board, chess piece.
Detail design the "move" action
Round 3 of the interview(in person).
given a binary tree with each node contains a number (with negative, duplicate number), write program to find the level which have the most num of negetive number.
Word Wrap / String Justification algorithm.
Given a set of words and a length.
You are required to print the words such that the words on each line end almost on the same column and the number of trailing spaces at the end is minimized.
Given aaa bb cc ddddd and length is 5 print the following output.
aaa
bb cc
ddddd
Given a huge file 100 million integers. He further divided the file into 100 files with 1 million integers in each and each file is sorted. Needed to find the k smallest integers.
I used the concept of min-heap. Take the first element from each file and construct a min-heap. Take the root,as it is the smallest element and insert the next element from the file which contains the root root element. Heapify the tree and repeat k times.
The interviewer asked if another efficient method exists?
write a program to write all combination for elements given in a list. (no of elements in given list are may vary)
for ex list = {1,2,3}
combinations:
1
2
3
12
13
23
123
select * from Employee, Department
will this query execute and in case yes what will be output, in case no why?
Class A
{ void print(){}
}
Class B extends A
{ void print(){}
public static void main(String args[])
{
B b = new A();
}
}
Whats wrong with the above piece of code?
will below mentioned line work?
B b = (B)new A();
How to find starting of loop in a link list in case looping somewhere.
For ex: 1->2->3->4->5->3
Given two stations at random, show all possible routes between those stations (if any)
- Stations links are listed below
- Links between stations are bi-directional
- Routes generated should not have cycles
cambridge<>stansted
stansted<> harlow
harlow<>london
london<>hatfield
hatfield<>peterborough
cambridge<>hatfield
cambridge<>ely
peterborough<>ely
peterborough<>birmingham
birmingham<>manchester
manchester<>glasgow
glasgow<>edinburgh
edinburgh<>newcastle
newcastle<>thirsk
thirsk<>york
york<>manchester
york<>peterborough
Given a number N. find is it perfect square or not. cannot use any library functions.
Merge N sorted linked list of integers
Constraint was :
min comparison and no extra memory(i given a solution with min heap, they told heap will take O(N) memory. so cant use it).
Difference between Trie and N-array tree.
Merge N sorted linked list of integer
Constraint was :
min comparison and no extra memory(i given a solution with min heap, they told heap will take O(N) memory. so cant use it).
Amazon is considering introducing a customer loyalty program, which rewards members with Amazon Dollars on purchases. The program encourages members to be sponsors and recruit other shoppers to join. Purchases made by recruits are then rewarded to the sponsor. The chain of recruits can be arbitrarily deep. Any purchase by a member is counted towards that member (10% of purchase price), their sponsor (4%), their sponsor’s sponsor (4% of 4%), their sponsor’s sponsor’s sponsor (4% of 4% of 4%), etc. Finally, a sponsor can have any number of recruits, but any one recruit can only have one sponsor.
Write a function that calculates the payout for a given member.
Given the following interface, please implement the MemberPayoutUtil.calculatePayout function.
public interface Member {
public double getMonthlyAmazonDollars();
public Collection<Member> getRecruitedMembers();
}
There is a party going on. A favorite group has to be found out. Suppose there are five people A, B, C, D and E.
A, B and C knows each other. D and E knows A, B and C. So ABC is the favorite group as all of them know each othe and
evry other in the party knows them. Question was How to find this group and which datastructure/algo will be suitable?
Given stock price of Amazon for some consecutive days. Need to find the maximum span of each day’s stock price. Span is the amount of days before the given day where the stock price is less than that of given day
E.g i/p = {2,4,6,9,5,1}
o/p= { -1,1,2,3,2,-1}
Given a matrix of characters and a string, find whether the string can be obtained from the matrix. From each character in the matrix, we can move up/down/right/left. for example, if the matrix[3][4] is
o f a s
l l q w
z o w k
and the string is follow, then the function should return true.
How would you maintain concurrency on a shared page being edited by multiple users simultaneously.
What if the page is being shared using a client- server mechanism. Represent the classes and explain the thread safety mechnism to avoid editing conflicts.
Given 2 strings str1 and str2. What is the efficient way to navigate from str1 to str2? The constraints are i) a string can be changed to another string by changing only one character. ii) all the intermediate strings must be present in dictionary. If not possible, return “not possible to navigate from str1 to str2″. (pre-processing is allowed and enough memory is available). for example: str1 = feel and str2 = pelt, then the navigation is feel -> fell -> felt -> pelt
Given a set of intervals like 5-10, 5-10, 8-12, 9-15
Find the ith smallest number in these intervals.
for eg:-
Suppose we have intervals like 5-10, 8-12.
Then total numbers in these two intervals would be: {5,6,7,8,8,9,9,10,10,11,12}
So, 1st smallest number: 5
4th smallest number: 8
5th smallest number: 8 (here is the
change since now we have duplicate elements also) and so on.
how to redirect the url to the custom url after the successful completion of the payment in the emppay gateway
How Hashmap works internally? Resizing? Hashbuckets' separation?
Array of Integers. Given Integer X, return true iff there exist A,B, so that A+B=X. Hint: additional data structure might be needed.
How would you store a phone book. Unique phone numbers, possibly multiple same names with different phone numbers.
Array of Integers with even number of same Integers. Find the Integer that is an odd number of times. Compare efficiency between different approaches.
Find next higher number with same digits.
Example 1 : if num = 25468, o/p = 25486
Example 2 : if num = 21765, o/p = 25167
Example 3 : If num = 54321, o/p = 54321 (cause it's not possible to gen a higher num than tiz with given digits ).
/*
* Returns true if the input string is a number and false otherwise
*/
public boolean isNumber(String toTest)
{
// implementation here
}/**
* Implement a method which takes an integer array and returns an integer array (of equal size) in
* which each element is the product of every number in the input array with the exception of the
* number at that index.
*
* Example:
* [3, 1, 4, 2] => [8, 24, 6, 12]
*/
public int[] selfExcludingProduct(int[] input) {
// implementation...
}Given a string, find the largest repetitive sequence. Algo + Code
Ex: abcdefbcd – bcd, banana – ana
Sliding window problem where window size is 3 and we need to find the minimum from the window.
Given a list with duplicate values find the first unique elements in it.
for eg: BH BH F AL HJ AL HJ PK
so answer is F
Given a matrix and need to traverse through it last position from first position and the matrix has 0 and 1 if there is 1 we cant proceed ahead.
Compare two release version and tell me which is larger
eg: 1.0.10 and 1.0.2
1.0.2 is greater
1.2.0 and 2.1.0
2.1.0 is greater
Given a list of 'N' coins, their values being in an array A[], return the minimum number of coins required to sum to 'S' (you can use as many coins you want). If it's not possible to sum to 'S', return -1
Example:
Input #00:
Coin denominations: { 1,3,5 }
Required sum (S): 11
Output #00:
3
Explanation:
The minimum number of coins requires is: 3 - 5 + 5 + 1 = 11;
Unable to get what exactly the Question Is?
so What is the whole logic behind this question .It seems to be complete Math problem to me.
There is a Grasshopper in a tropical forest. The grasshopper can jump only vertically and horizontally, and the length of jump is always equal to x centimeter. A GRasshopper has found herself at the center of some cell of the chess board of the size pxq centimeters(each cell is 1x1 centimeters). She can jump as she wishes for an arbitrary number of times, she can even visit a cell more than once. the only restriction is that she cannot jump out of the board.
The grasshopper can count the number of cells that she can reach from the starting position(x,y). Let's denote this amount by dx,y. your task is to find the number of such starting position(x,y), which have the maximum possible value of dx,y
Input
The integer array contains three integers p,q,x
p= length of the board
q= width of the board
x=length of the grasshoppers jump.
Output
Output the only integer - the number of the required starting position of the Grasshopper
Example
input 2 3 1000000
output 6
input 3 3 2
output 4
Regards,
JSD
Write a function to convert an Integer representing a number of bytes (less than or equal to 1 Gigabyte) into an easy to read format, defined as follows: • Maximum of 3 digits (not counting a decimal point), and a single letter to signify the unit of measure. • No leading zeroes, or trailing zeroes after a decimal point. • Be as accurate as possible.
Maximum of 3 digits (not counting a decimal point), and a single letter to signify the unit of measure. • Round to the nearest valid values. Examples: o 341 = 341B o 34200 = 34.2K o 5910000 = 5.91M o 1000000000 = 1G • No leading zeroes, or trailing zeroes after a decimal point. Examples: o 34K, not 034K o 7.2M, not 7.20M • Be as accurate as possible. Example: o 54123B = 54.1K, not 54K • Note: For this problem, 1000 bytes = 1 KB, and so on
Given a paragraph of text, write a program to find the first shortest sub-segment that contains each of the given k words at least once. A segment is said to be shorter than other if it contains less number of words
divide a given array into two subarray (not necessary to be continuous) such that difference between sum of both array is minimum. Required was recursive code for this. tried solving using idea from min coin change problem was couldn't.
Print the diameter of binary tree i.e. set of nodes comprising diameter of binary tree.
Find the smallest window in a string containing all characters of another string
count the consecutive chars in a string.
Example input string: BBSBSS
output string: B2S1B1S2
* ignore case . out put is always uppercase
input : AaV
output: A2V1
count the consecutive chars in a string.
Example input string: BBSBSS
output string: B2S1B1S2
* ignore case . out put is always uppercase
input : AaV
output: A1V1
Given an excel column number convert it to excel column alphabet and reverse.
Example : If column number(starts from 0) = 26 : Column alpha = AA.
Find if the given expression contains redundant parantheses. ex :if expr = a+(b*c) , print false, if expr = a+((b*c)), print true.
COUNT 1s in BINARY FORMAT OF A NUMBER.
Given a matrix with only 1s and 0s now find and PRINT SUB MATRIX WITH EQUAL NUMBER OF 0s AND 1s.
Given a list of stock quotes over a month of time,
Return the buy day and sell day which gives the max
profit.
given a set of n meetings and m meeting rooms, how will you schedule the meetings in the meeting rooms?
you have an array which has a set of positive and negative numbers, print all the subset sum which is equal to 0.
eg 2, 1, -1, 0, 2, -1, -1
o/p: 1, -1
1, -1, 0
0
2, -1, -1
Write the following functions to serialize a vector of strings to a string and read it back(possibly on another machine):
string encode(vector<string> v);
vector<string> decode(vector<string> v);
Given two strings, write an efficient algorithm (in Java) to compare the two of them. Your algorithm should handle all cases
Further on, the design tables and more SQL queries given some business requirements. And how would I do the same using MapReduce.
The question was I have a table containing millions of records and I have to calculate sum, avg, mean, median and SD without using inbuilt methods of SQL ( I can use count though).
And that has to done by writing only SQL queries.`
public enum State {
2 Unvisited, Visited, Visiting;
3 }
4
5 public static boolean search(Graph g, Node start, Node end) {
6 LinkedList<Node> q = new LinkedList<Node>(); // operates as Stack
7 for (Node u : g.getNodes()) {
8 u.state = State.Unvisited;
9 }
10 start.state = State.Visiting;
11 q.add(start);
12 Node u;
13 while(!q.isEmpty()) {
14 u = q.removeFirst(); // i.e., pop()
15 if (u != null) {
16 for (Node v : u.getAdjacent()) {
17 if (v.state == State.Unvisited) {
18 if (v == end) {
19 return true;
20 } else {
21 v.state = State.Visiting;
22 q.add(v);
23 }
24 }
25 }
26 u.state = State.Visited;
27 }
28 }
29 return false;
30 }
plz explain me the code
Suppose your team needs to launch a new recommendation feature called “Stuff Your Friends are Buying”. The recommendation logic is based on the following rules:
• A customer should only be recommended product that their friends bought but they haven’t bought.
• The recommendations priority is driven by how many friends have purchased the same item – if multiple friends purchased the same item, it should be higher in the recommendations than a product that only one friend owns.
You are provided two library functions to help you
• getFriendsListForUser – returns a list of customer IDs (strings that uniquely identify an Amazon user) representing the friends of an Amazon user
• getPurchasesForUser – returns a list of product IDs (strings that uniquely identify an item in the Amazon catalog) for an Amazon user ordered by purchase time with newest purchase first in list and oldest purchase last in list
For this evaluation, please:
1) Write a function that provides a ranked (high to low) list of recommendations (product IDs) for a provided user.
2) Write code for a few key unit tests for your code.
3) Enumerate other unit test scenarios (code not required).
4) Provide the space and time complexity of your solution.
Suppose your team needs to launch a new recommendation feature called “Stuff Your Friends are Buying”. The recommendation logic is based on the following rules:
• A customer should only be recommended product that their friends bought but they haven’t bought.
• The recommendations priority is driven by how many friends have purchased the same item – if multiple friends purchased the same item, it should be higher in the recommendations than a product that only one friend owns.
You are provided two library functions to help you
• getFriendsListForUser – returns a list of customer IDs (strings that uniquely identify an Amazon user) representing the friends of an Amazon user
• getPurchasesForUser – returns a list of product IDs (strings that uniquely identify an item in the Amazon catalog) for an Amazon user ordered by purchase time with newest purchase first in list and oldest purchase last in list
1) Write a function that provides a ranked (high to low) list of recommendations (product IDs) for a provided user.
2) Write code for a few key unit tests for your code.
3) Enumerate other unit test scenarios (code not required).
4) Provide the space and time complexity of your solution.
2) Determine if an email is a spam or not if any of the spam token is available in the subject line. Spammers repeat some or all of the characters to make the spam check fail, and allow the spam. Handle that condition as well.
blob => bbbblllllllooooooooobbbbbbbbb
cool => ccccccooollllllllllllll
cool => cccccollll (this word is not spam as letter o is not repeated atleast twice)
You are given a 2D array and each cell has some eggs in it represented by a number. you have to start at (0,0) you can either move right or left. now when you reach (m,n) you shd hav collected max eggs. WAP to print max number of eggs that can be collected in a given matrix.
SUM OF PREVIOUS SMALLER NUMBERS IN ARRAY efficiently. For every given element in the array you should return the sum of previous smaller values you encountered in the array . example : arr = {2, 5,1,9, 3}
for a[0] i.e. 2 , sum = 0, a[1] i.e. 5, sum = 2, similarly for a[4], i.e. 3 , sum = 2+1 = 3.
write "bool isSplitable(int[] arr)" to return true if the arr can be divided into two parts having the equal sums; return false otherwise.
At your disposal you have 100 processing nodes. You have 1 billion rows of data which are located on the storage attached to one processor. All the processors can read from the storage of any other processor over a network. The objective is to sum one of the columns of the data set with minimum cost(time).
Cost summary
a. 0.01 unit(of time) to read 1 row of data from a local processor
b. 0.05 unit (of time) to read 1 row of data from a remote processor
c. 1000 units(of time) to partition the file into two pieces.
d. 0.1 unit(of time) to copy 1 row of data from a remote processor to a local processor
e. 1 unit(of time) to sum 1 row of data
What is the optimal configuration of the system to sum 1 column of the data file with the minimum cost(time)? Consider location of the data, the partitioning of the data, the number of processors to be used.
How many squares are present in an NxN grid?
In an MxN grid, how many squares are present and how many rectangles?
At your disposal you have 100 processing nodes. You have 1 billion rows of data which are located on the storage attached to one processor. All the processors can read from the storage of any other processor over a network. The objective is to sum one of the columns of the data set with minimum cost(time).
Cost summary
a. 0.01 unit(of time) to read 1 row of data from a local processor
b. 0.05 unit (of time) to read 1 row of data from a remote processor
c. 1000 units(of time) to partition the file into two pieces.
d. 0.1 unit(of time) to copy 1 row of data from a remote processor to a local processor
e. 1 unit(of time) to sum 1 row of data
What is the optimal configuration of the system to sum 1 column of the data file with the minimum cost(time)? Consider location of the data, the partitioning of the data, the number of processors to be used.
Given an array, you should start at index 0, and you can jump
from the current index to a max of " current index + arr[current index]
and make it out of the array at the other end in minimum number of hops.
Write code to generate all possible case combinations of a given lower-cased string. (e.g.
"0ab" -> ["0ab", "0aB", "0Ab", "0AB"])Write a program to evaluate arithmetic/math expression
"12 + 5*4 + 26" = 58
"5 * 4" = 20
"6 + 4" = 10
"12" = 12
Write a program to find all telephone numbers from a file
of this pattern (xxx) xxx-xxxx
xxx-xxx-xxxx (Come up with a regex)
A number series have numbers in the increasing order where numbers are of the form 2^m*3^n*5^p. where m,n,p are an non negative integers. The initial few number of the series are
1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 16, 18......
Write a function to get the nth term of such a sequence.
Given a undirected graph with corresponding edges. Find the number of possible triangles?
Example:
0 1
2 1
0 2
4 1
Answer:
1
You have the file with word at a single line.
#input sample file
abactor
abaculus
abacus
Abadite
.
.
Zyrenian
#Output
******************************************************************a
*************b
**********************************c
**********************d
*******************************************************************************e
a) you have to count the character and create a histogram in alphabetical order.
b) now you have to produce a histogram with max 80 character in line in reference to max count
c) now same out based histrogram based on the character count
Given a current absolute path, e.g., "/usr/bin/mail", and a relative one, e.g, "../../../etc/xyz/../abc" return the absolute path created from the combination of the first two paths. In the example strings, the answer should be "/etc/abc".
Setup:
Assume primitive Facebook. FB has Members.
class Member {
String name;
String email;
List<Member> friends;
}
Question A:
Code printSocialGraph(Member m). Direct friends of m are Level 1 friends. Friends of friends are level 2 friends.....and so on
Print level 1 friends first. Then print level 2 friends....and so on
Given a string, write an algo and code to print all possible anagrams for given string.
for ex:
Given string: "amz"
Output:
amz
azm
maz
mza
zam
zma
Note: Write Algo and Code
Assuming your laptop is a fresh one.. It is just connected to your LAN. There is no static config available. typing "google.com". what will happen ? can someone clarify me.
what will happen if it is a PPPoE connection ?
what will happen if it is a IPoE connection ?
please explain them separately
Build a binary tree using it's inorder & levelorder tree traversal.
Asked to explain how to check Binary tree is BST?
Find Nodes which are at "K" distance from given node.
Find In order predecessor in BST.
asked me about assembly line problem.
asked me to solve Knapsack Problem
Asked to explain how to check Binary tree is BST?
then asked me to write whole code of it.
Find Nodes which are at "K" distance from given node.
explain logic and write full code with all boundary conditions.
Find In order predecessor in BST.
explain logic and write full code with all boundary conditions.
Given two strings a and b, find whether any anagram of string a is a sub-string of string b. For eg:
if a = xyz and b = afdgzyxksldfm then the program should return true.
Implement a sorting algorithm for a single linked list.
Given a mapping configuration such as:
1:a
2:b
...
26:z
And a string like "12632", print the number of different ways you can map such string to alphabet characters.
For example, given "111" the answer is 3 because you can make "aaa", "ak" and "ka" different mappings. However, given "101" the answer is 1 because you can only make "ja" as a possible mapping (01 is not valid).
Print all paths of a binary tree from root to leaf.
Later, extend the solution to work with graphs, careful attention to cycles which you should print as paths as well (without printing visited nodes twice).
given a board with black (1) and white (0), black are all connected. find the min rectangle that contains all black.
example:
0 0 0 0 0
0 1 1 1 0
0 1 1 0 0
0 1 0 0 0
0 0 0 0 0
the min rectangle contains all black (1) is the rectangle from (1,1) - (3, 3)
Given an array of Integers, and a range (low, high), find all continuous subsequences in the array which have sum in the range. Is there a solution better than O(n^2)?
Write a class that displays average of stock prices for a given stock symbol for the last 10 minutes. We have a service that sends stock updates about 5000 times per second. The structure of the message is :
Message {
long timestamp;
String symbol; // E.g. AAPL
double price;
}Given k integers i_0, i_1, i_2, i_3,...i_k, find all possible expressions which uses + - * / and () to generate a result equals to target X.
() has the highest priority.
Generate all numbers in ascending order which are having factors as 2,3 and 5. Discuss various approaches.
You are trying to control an on-screen keyboard (e.g. on a television) that looks like this:
a b c d e
f g h i j
...
You can issue the following commands to move the cursor and select letters:
‘u’ - up
‘d’ - down
‘l’ - left
‘r’ - right
‘!’ - select letter
You are given an input string and the length of the rows in the on-screen keyboard. You must produce the sequence of commands needed to type out the input string on the specified keyboard, e.g.:
“aci”, 5 -> “!rr!dr!”
Given a dictionary of words, and a set of characters, judge if all the characters can form the words from the dictionary, without any characters left.
For example, given the dictionary {hello, world, is, my, first, program},
if the characters set is "iiifrssst", you should return 'true' because you can form {is, is, first} from the set;
if the character set is "eiifrsst", you should return 'false' because you cannot use all the characters from the set.
P.S. there may be tens of thousands of words in the dictionary, and the chars set length could be up to hundreds, so I really need some efficient algorithm.
Rearrange an array so that arr[i] becomes arr[arr[i]] with O(1) extra space
Queue implementation in Java.
Given an array of integer, find the minimum in the sliding window of size 4, in most optimal way.
ex [2,1,3,4,6,3,8,9,10,12,56]
Output : [1,1,3,3,3,3,8.....]
Design an iterator for a given stream of integers, with next() and hasnext() being called in any sequence, but skipping any 0's in the stream.
Find if a given array has any duplicates, with O(n) complexity
Given n array return true if there exist a element from each array whose sum is zero
Machine coding round : (Time 1hr)
expression is given and a string testCase, need to evaluate the testCase is valid or not for Expression
Expression may contain letters [a-z]
Expression may contain "."( '.' represents any char in [a-z])
Expression may contain '*'( '*' has same property as in normal RegExp)
Expression may contain '^' ( '^' represents start of the String)
Expression may contain '$' ('$' represents end of String )
Sample cases (Exp, testCase, Result) below
1. ab, ab , true
2. a*b , aaaaaab , true
3. a*b*c*, abc , true
4. a*b*c , aaabccc, false
5. ^abc*b, abccccb , true
6 ^abc*b, abbccccb , false
7 ^abcd$, abcd , true
8 ^abc*abc$ , abcabc, true
9 ^abc.abc$, abczabc , true
9 ^ab..*abc$, abyxxxxabc, true
Coding in Computer : (Time 1hr)
Expression is given and a string testCase, need to evaluate the testCase is valid or not for Expression
Expression may contain letters [a-z]
Expression may contain "."( '.' represents any char in [a-z])
Expression may contain '*'( '*' has same property as in normal RegExp)
Expression may contain '^' ( '^' represents start of the String)
Expression may contain '$' ('$' represents end of String )
Sample cases (Exp, testCase, Result) below
1. ab, ab , true
2. a*b , aaaaaab , true
3. a*b*c*, abc , true
4. a*b*c , aabccc, false
5. ^abc*b, abccccb , true
6 ^abc*b, abbccccb , false
7 ^abcd$, abcd , true
8 ^abc*abc$ , abcabc, true
9 ^abc.abc$, abczabc , true
9 ^ab..*abc$, abyxxxxabc, true
Given a couple of integer arrays A = {2, 4, 3, 5, 6, 8} & B = {9, 2, 7, 6} - Return the intersection of these arrays.
Once I provided a solution (which was n squared -O (n^2)) he followed up by asking me if I could make it linear (O(n)).
Write a method which will accept a string and return true if the string is a palindrome and false if it isn't.
Special conditions:
a) your method should consider lower case and upper case characters to be the same.
b) your method should ignore special characters and white spaces, for e.g. if your input were the strings were "Madam, I'm Adam!!", then you should consider it a palindrome and hence return true ignoring case and special characters. Same with inputs like "Ma'am", "boB" etc should return true.
Write a function accepting a string with numbers and letters that reverses the letters of the string but leave numbers in the same position.
Example input: str1ngw1thnumb3rs
Example output: srb1mun1htwgn3rts
Given an input integer array, write a function that returns an array such that all the low numbers in the input array are sorted before all the medium numbers in the input array, which come before all the high numbers in the array.
You can assume that someone has written functions for you like:
public boolean isLow(int input);
public boolean isMedium(int input);
public boolean isHigh(int input);
You can also assume that every int will fall into one (and only one) of these categories.
For example:
if < 0 is low, > 100 high, 0-100 medium
input: [3, -1, 105, 108]
valid outputs: [-1, 3, 105, 108] or [-1, 3, 108, 105]
*/
I was able to solve this in linear time and linear space. How can it be done in linear time with constant space??
Compare time complexity of insert and search functions in HashMap, Array, Linked List and Queue
Find largest element in an array
Given two extremely large numbers - each number is stored in a Singly Linked list, with the MSB at the head. You are not allowed to reverse the Linked lists. Write a program to multiply them in optimum space and time.
Many sticks with length, every time combine two, the cost is the sum of two sticks' length. Finally, it will become a stick, what's the minimum cost?
HashMap<Integer,Integer> hs = new HashMap<Integer,Integer>();
hs.put(1,1);
hs.put(1,2);
when call hs.get(1) it return 2 i want first 1,so how to get this
We can start a Thread using either of two methods start() and run().What is the difference between these two?
How would you find a random non-null element from an array of 10 million, where most elements are null, in a reasonable amount of time?
There are 5 buckets filled with coins. Real coins weigh one gram each, and fake coins weigh 0.9 grams each. Each bucket is either fake (contains only fake coins) or real (contains only real coins). Given the number of buckets is fixed(say 5) how many coins should each bucket contain so that the it is possible to find/locate fake buckets vs real buckets in 1 weighing(use of the machine). Also, find the sequence of coins which have to be selected from each bucket ?
Here more than one bucket could be fake. Also, each bucket could either be fake or real. All buckets contains same number of coins.
An integer array contains elements in increasing order till some point and then decreasing order , return the index of maximum number. Solution should be less than O(n). Ex - {1,2,3,4,5,3,1}
Given a larger integer buffer/array (say size, x), now given a window size (say, n) and a number (say, k). Windows starts from the 1st element and keeps shifting right by one element. The objective is to find the minimum k numbers present in each window.
There is a village in which parent prefer to have at least 1 boy. So they keep doing child until they get their first boy and then they stop doing children. What is ratio of girl/boy in such town after infinite years.
You are given a large set of integers, which are not sorted. Figure out a method to retrieve the largest 1000 elements, in O(n) run time
multiplication of two numbers without actual multiplication ::
Using vedic mathematics
Having trouble with this array pair difference problem (NOT array pair sum) because of a certain edge case.
Example is: k = 4 a = [ 1, 1, 5, 6, 9, 16, 27] output: 3 (Due to 2x [1, 5], and [5, 9])
So, find the difference that equals to k. I used this code in my interview but realized it was wrong hours later unfortunately. It only gives 2.
public static int arrayPairDifference(int[] a, int k)
{
HashMap<Integer, Integer> hashMap = new HashMap<>();
int count = 0;
for (int i = 0; i < a.length; i++)
{
if (hashMap.containsValue(a[i] - k))
{
count++;
}
hashMap.put(i, a[i]);
}
return count;
}How to account for the edge case of the 2x [1, 5] ?
Operation :Deleting element in the binary search tree(Without linked list) I'm trying to implement a pseudo-code but operation not implemented.can cause?(If you want I can write a pseudo-code.)So,delete operation is not happening for BST.can cause?-1 is null element in array. Linked list is not be for this code.
void deleting(int *Tree,int element){
int temp=0;
while((Tree[temp]!=element) && (Tree[temp]!=-1)){
/*loop until the element is found*/
if(element<Tree[temp])
temp=2*temp+1;
else
temp=2*temp+2;
}
if(Tree[temp]!=1)/* if the element is found*/
/*case1 - Delete leaf node*/
if((Tree[2*temp+1]==-1) && (Tree[2*temp+2]==-1))
Tree[temp]=-1
/*case 2- delete node with one child*/
else if((Tree[2*temp+1]==-1)|| (Tree[2*temp+2]==-1)){
if(Tree[2*temp+1]!=-1) /* is the child in the left of temp*/
preOrder((2*temp+1),Tree);
else
preOrder((2*temp+2),Tree);
}
/*case 3-delete node with 2 children*/
else if {
int inOrder_N=2*temp+2 /* inorder successor is surely in the right sub tree*/
while(Tree[2*inOrder_N]!=-1)
inOrder_N=2*inOrder_N;
Tree[temp]=Tree[inOrder_N]; /* replace with inorder successor*/
if(Tree[2*inOrder_N+2]==-1);/* inorder successor has no child*/
Tree[inOrder_N]=-1;
else /* inorder successor has no child*/
preOrder(((2*inOrder_N)+1),Tree)
}
else
printf("element not found");
}
void preOrder(int node, int *bst,int n){
if(node<n){
printf("Node : %d - Value : %d \n",node,bst[node]);
preOrder(2*node+1,bst,N);
preOrder(2*node+2,bst,N);
}
return;
}
Given a dictionary, and a list of letters ( or consider as a string), find the longest word that only uses letters from the string. [I didn't meet this question, what's the best solution?]
Given 2 strings S1 and S2 where length of each string can go upto 10^5 I need to find Longest Common Substring of the two strings (Both its length and Substring also).
If their are many substrings with same maximum length I need to find that substring which occurs earliest in S2.
EXAMPLE : Let S1=defghi and S2=ghidef Then here answer will be ghi and length is 3.
I tried implemented it using suffix array but got stuck in between.Could someone help and provide the code to do it in c++/java
Note : It was mentioned that length of S1 is always greater or equal to length of S2
Say you were assigned the task to optimize a website, what would you do first?
Insert a element in a sorted circular linked list
For a given node in binary search tree find a next largest number in search tree.
Write a function return an integer that satisfies the following conditions:
1) positive integer
2) no repeated digits, eg., 123 (valid), 122 (invalid)
3) incremental digit sequence, eg., 1234 (valid) 1243(invalid)
4) the returned integer MUST be the smallest one that greater than the input. eg., input=987, return=1023
function signature could be like this:
String nextInteger(String input)
Given a 2-D matrix represents the room, obstacle and guard like the following (0 is room, B->obstacle, G-> Guard):
0 0 0
B G G
B 0 0
calculate the steps from a room to nearest Guard and set the matrix, like this
2 1 1
B G G
B 1 1
Write the algorithm, with optimal solution.
Deck of cards :
1) Put the first card on the table and next at the bottom of the deck
2) Repeat the above until all the cards are on table.
3) Pick up the cards and repeat steps 1 and 2.
Find after how many iterations the original order is restored.
For Ex ::
1 2 3
1st iteration - 2 3 1
2nd iteration - 3 1 2
3rd iteration - 1 2 3
so after 3 iterations. Find for n.
2 players place the knight in his desired postion (input taken from user) on chess board.The knights move in valid knight postions in chess.2 knights move one after the other.game ends when any one knight reaches bottom right corner.
Given a N*N adjacency matrix of graph I need to find the size of maximum set of vertices that do not share any common edge between any two vertices of the graph.
Like : Say we have 3*3 matrix as
0 1 0
1 0 1
0 1 0
Then here answer is 2 as vertex 1 and vertex 3 dont have any edge in common.
I was asked this question in my interview to implement it in c++.
IF we remove next line character then program runs fine else it gives a seg fault
#include <stdio.h>
void main()
{
char *a[10] = {"hi", "hello", "how"};
int i = 0, j = 0;
a[0] = "hey";
for (i = 0;i < 10; i++)
printf("%s\n", a[i]);
}Understand the Elevator_Operations class definition below and expand the solution:
class Elevator_Operations
{
private:
int number_of_persons;
public:
virtual void move_up() = 0;
virtual void move_down()= 0;
virtual void next_stop() =0;
void set_max_persons(int number_of_persons);
void set_max_weight(float weight_in_kilograms);
int get_current_floor();
int get_next_destination_floor();
virtual void overload_alert(int currentLoad)=0;
};
1) Program must be customizable for different buildings having varying number of floors
2) Method to set the maximum weight and number of persons an elevator can support
3) Method to display alert message when elevator is overloaded, along with the current load
4) At any part of the program current floor and next destination floor details must be made available
5) Code to control the movement of the elevator should be defined only in child class as the working
mechanism varies based on the usage.eg: elevator moves to the very next floor up/down or moves to the
floor which was chosen by the first user, then the next user etc
6) Once destination is reached write a code to open the door; similarly, to close the door after the user
decides
destination floor
You are given a string which has numbers and letters. Numbers occupy all odd positions and letters even positions. You need to transform this string such that all letters move to front of array, and all numbers at the end.
The relative order of the letters and numbers needs to be preserved
I need to do this in O(n) time and O(1) space.
eg: a1b2c3d4 -> abcd1234 , x3y4z6 -> xyz346
Please don't submit your answers if it is not fulfilling the time-space complexity requirements.
Program to count all Response codes individually per database ( slideshare_backedn_fe01 is one db) in the given log file'
output should like this
{
backend : backend name
{
200: 20
503: 3 where 3 is count of response codes 503
}
}
once again logfile looks like this
May 29 13:53:13 127.0.0.1 haproxy[27326]: 164.85.131.129:15592 [29/May/2013:13:53:13.671] slideshare slideshare_backend/fe01 1/0/1/106/296 200 451 - - --VN 1526/1526/837/402/0 0/0 {www.slideshare.net|Mozilla/5.0 (Windows NT 5.1; rv:10.0.4) Gecko/20100101 Firefox/10.0.4|http://www.slideshare.net/slideshow/embed_code/11959978?hostedIn=slideshare&referer=http://www.slideshare.net/goulart.sousa|} {2471317690|||pingback/embed_or_homepageplayerhits|s11959978/a8717995|} "GET /pingback/embed_or_homepageplayerhits/11959978?ref=http%3A%2F%2Fwww.slideshare.net
%2Fgoulart.sousa&_=1369853592559 HTTP/1.1"
May 29 13:53:13 127.0.0.1 haproxy[27326]: 217.129.26.81:50910 [29/May/2013:13:53:13.724] slideshare slideshare_backend/fe02 17/0/0/1/246 200 3291 - - --VN 1529/1529/839/435/0 0/0 {www.slideshare.net|Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.0; Trident/5.0)|http://www.slideshare.net/inexita/4|} {1098476889 1090975733|||||} "GET /images/fadedlogo.jpg?829e162373dc3b1cc145ba5b62aba32c8c804b67 HTTP/1.1"
May 29 13:53:13 127.0.0.1 haproxy[27326]: 79.154.237.97:50310 [29/May/2013:13:53:13.758] slideshare autosuggest_backend/solrsearch10_01 13/0/0/3/212 200 526 - - ---- 1528/1528/17/3/0 0/0 {autosuggest.slideshare.net|Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.94 Safari/537.36|http://www.slideshare.net/faroviejo/las-10-ciudades-ms-grandes-del-mundo-y-la-paz-bcs|} {|||||} "GET /?q=las?10?ciudades?ma*&rows=5&wt=json&sort=frequency%20desc&fq=%2Bresults%3A%5B10%20TO%20*%5D&json.wrf=jQuery17209988682114053518_1369853526684&_=1369853590254 HTTP/1.1"
In a Binary tree, every element(node's value) must contain the sum of its left and right sub-trees.
Follow up question: how would you solve this if you can ONLY increment the value of a node
Eg. If a node’s value is 20 and its sub-tree sum is 10, the node’s value can’t be set to 10 because you can only increment.
How would you solve this if you can ONLY increment the value of a node
Further clarifications.
1. You can make assumption that leaf nodes retain their original value and does not change.
2. "Sum of its left and right subtrees" means sum of all nodes' values in its left subtree + sum of all nodes' values in its right subtree.
PS: I am asking this question coz I am not sure of its solution myself. Hence seeking experts' advice.
how to print this pattern
input N=4
output :
4444444
4333334
4322234
4321234
4322234
4333334
4444444
input N=3
output :
33333
32223
32123
32223
33333
Print the Pattern
input N=4
output :
4444444
4333334
4322234
4321234
4322234
4333334
4444444
input n=3
output :
N=3
33333
32223
32123
32223
33333
In Amazon web site, the product items has to show with different attributes combination for clothers.
Example:
color - red blue green
size - XL X M S
pattern - checks lines
so output should be in below format in different combinations:
red - xL - checks
red - xL - lines
red - X - checks
red - x - lines
red - M - checks
:
:
green - S - checks
green - S - lines
Note:- In above example, no. of attributes is 3. but attributes can be N.
Below is the code, I have written. Hope it will be useful for anyone.
This is an non-recursive logic which will work for large value of N. time Complexity is O(n2).
-------------------------------------------------------------------------------------
package com.test;
import java.util.Scanner;
public class Solution
{
public static void main(String args[] ) throws Exception
{
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
Scanner in = new Scanner(System.in);
int n = in.nextInt();
in.nextLine(); //to read new line
String[][] attributes = new String[n][];
int i=0;
while(i < n)
{
String temp = in.nextLine();
String[] values = temp.split(" ");
attributes[i] = values;
i++;
}
printAttributesCombination(attributes);
}
static void printAttributesCombination(String[][] attributes)
{
int count[] = new int[attributes.length];
int totalcount[] = new int[attributes.length];
//initialize the totalcount and temp index count
initialize(count, totalcount, attributes);
while(isDone(count,totalcount))
{
printArray(attributes,count);
}
}
static void initialize(int count[], int totalcount[], String[][] attributes)
{
for(int i = 0; i < count.length; i++)
{
count[i] = 0;
totalcount[i] = attributes[i].length - 1;
}
count[count.length-1] = -1;
}
static boolean isDone(int count[], int totalCount[])
{
boolean prevIndexSet = true;
boolean canTerminateLoop = false;
int i = 0;
for(i = count.length - 1; i >= 0 ; i--)
{
if(count[i] == totalCount[i])
{
count[i] = 0;
prevIndexSet = true;
canTerminateLoop = true;
}
else
{
count[i] = count[i] + 1;
prevIndexSet = false;
canTerminateLoop = false;
}
if(!prevIndexSet)
break;
}
if(canTerminateLoop && i == -1 )
return false;
return true;
}
static void printArray(String[][] arr, int count[])
{
System.out.println();
for(int i = 0; i < arr.length; i++)
{
System.out.print(" " + arr[i][count[i]]);
}
}
}
-------------------------------------------------------------------------------------Output:
==============
Sample1:-
============
3
a b c
d e f
g h i
a d g
a d h
a d i
a e g
a e h
a e i
a f g
a f h
a f i
b d g
b d h
b d i
b e g
b e h
b e i
b f g
b f h
b f i
c d g
c d h
c d i
c e g
c e h
c e i
c f g
c f h
c f i
Sample2:-
============
4
a b
a b c
d e
f i
a a d f
a a d i
a a e f
a a e i
a b d f
a b d i
a b e f
a b e i
a c d f
a c d i
a c e f
a c e i
b a d f
b a d i
b a e f
b a e i
b b d f
b b d i
b b e f
b b e i
b c d f
b c d i
b c e f
b c e i
input [2,3,1,4]
output [12,8,24,6]
Multiply all fields except it's own position.
Restrictions:
1. no use of division
2. complexity in O(n)
What would happen if you have only one server for a web cache (a web browser cache whose key is url and value is the loaded content of the webpage) but huge numbers of clients? And how would you solve it? Assume the cache is implemented with a hashmap and a linkedlist.
Write a program to accept a nonempty string of alphanumeric characters. Define a “run” as a
consecutive sequence of a single character. For example, “aaaa” is a run of length 4. The program will
print the longest run in the given string. If there is no single longest run, then you may print any of
those runs whose length is at least as long as all other runs in the string.
Example input: a
Example output: a
Example input: aab
Example output: aa
Example input: abbbbbcc
Example output: bbbbb
Example input: aabbccdd
Example output: aa
Write a program to accept a nonempty string of 0's and 1's as an argument. The program will print the
offsets of runs, each run consisting of all 0's or all 1's, where the runs are longer than 1. For example, if
given "0010011" it will print "0, 3, 5" on stdout.
There is a file which contains N words. There may be M anagrams in that file, K words on each anagrams. K>=1, M>=1, N>=1. You need to write an algorithm which will create one list for each anagram with k words and group all M lists with one data structure
Find your own method to balance an unbalanced binary tree.(you must not use existing methods like AVL, red black or b trees)
Convert a sorted integer Array to balanced binary search tree. This is very simple one and I could do it in O(n) time and O(1)extra space
Given 2 sorted linked list , merge them into single sorted list. Change the pointers, don't copy data
Given a read only linked list with next and random pointer , clone the list
It was a design question. You have to design a game. it has different types of monsters and different weapons. hero would shoot monster. each monster would have some initial health. Each weapon would do some predefined damage to monster. when its health gets 0, monster would die/disappear. and there would be multiple levels. based on level, monster and their behavior would change.
Given 2 rectangles , find whether they are overlapping or not.
delete all the nodes from a binary tree that lie on a path whose sum from root to leaf is less than a given value K. Twist was that the node values can be any integer. It may be a negative number.
Data structure to push, pop and find min element in O(1) time.
Given a linked list like a1-a2-a3-a4-b1-b2-b3-b4. Convert it into a1-b1-a2-b2-a3-b3-a4-b4
Given a MXN matrix. To find the number of ways to reach the mth row and nth column cell from 0,0 cell. Find the same if some of the cells are marked as not reachable.
Consider a scenario where you open a file with your favorite editor (emacs on Linux or Microsoft Word on Windows).
You notice that the application has a performance hit due to a recent fix made to the Editor application.
What will your testing Matrix look like that will convey the information that the performance of the application has degraded (or improved after bug fixes and re-design)?
In other words, the interviewer was saying that, if we had a graph showing values obtained from tests run over time for:
File I/O, hardware configuration, software configuration, graphics system, GPU, CPU etc.
then at the End Of the Day, looking at the reports, which parameters will instantly tell you that the performance has definitely increased?
(Also in other words he was asking the Matrix that will portray those parameters).
Given a matrix with 1's and 0's, a rectangle can be made with 1's. What is the maximum area of the rectangle.
00010
11100
11110
11000
11010 In this test case the result needs to be 8.
How:
00010 00010
11100 11 100
11110 11 110
11000 11 000
11010 11 010
If you see above the 11's are used from the first two columns and last four rows making the area or count of 1's to be 8.
What do you think is the next big thing in technology? For example, search engine is Google, social media is Facebook, etc. etc...
"How would you find the number of gas stations in the United States?"
*You cannot look up any concrete information (like the average number of gas stations per state), but you need to yield an accurate answer.
Implement a class that does string manipulation by overloading the following operators: <<, >>, = and ==. For example consider the following code:
StrShift example;
example = “Microsoft”;
printf(“\”example << 2\” results in %s\n“, example << 2);
In the above code the output would be “ftMicroso” which shows the last two characters of the string “Microsoft” rotated to the left of the string. Please note that state is maintained so two calls of example << 1 would give the same end result as calling example << 2 once.
3. Write a class that represents a minimal heap. The heap class should at a minimum support the following methods:
- AllocTinyHeap() which should initialize the heap with a given amount of bytes
- DeleteTinyHeap() which frees all memory associated with the heap
- TinyAlloc() which allocates a given number of bytes on the heap if there is room
- TinyFree() which frees a specific location on the heap
You may define whatever parameters are necessary for the above methods as well as write any additional methods. Overall consideration will be given to correctness, design, code readability as well as any unit testing done. As part of a final solution please submit test cases you used to verify correctness in addition to any unit tests done.
Write a recursive Method int shortestPath(int start, int end) in Java which returns the length of the shortest Path between start and end.
public class GraphMatrix {
public GraphMatrix(int iNrOfNode){
m_Matrix = new boolean[iNrOfNodes][iNrOfNodes];
}
private boolean[][] m_Matrix;
}types of index, diff between table and view
stored procedures, slow performance query tuning
String pool, equals method, create immutable class Person
collection Concurrency, blocked collection, dQueue, multi threading
Design a game of chess and explain?
Write a one liner in bash to count the number of phone numbers in a file using regular
expressions with sed and/or grep (keep in mind all the different types of ways people
write phone numbers)?
How much time does it take to fill up a floppy disk?
How does traceroute work?
Difference between ping and traceroute?
What is exactly in an A record?
Difference between A record and CName?
Name some DNS records and their purposes.
Difference between inner join and left join?
What is the default port for mysql?
What is inside a packet?
Difference between Active and Passive FTP?
I type www.Amazon.com into the browser and click go, explain in detail what happens?
Move the first n numbers in a 10 element array to the end.
I think the way to do it was to reverse the array and then reverse the first 10-n and then the last n.
What would be the O/P and why?
#include<stdio.h>
#include<conio.h>
int main()
{
int k = -7;
printf("%d", 0 < !k);
return 0;}
Imagine x is an operand and * is a binary operator. We say a string of x and * follows Reverse Polish notation if it is a postfix notation.
For example strings xx*, x, and xx*xx** follow Reverse Polish notation.
Given a string of x and *, how many insert, delete, and replace operations are needed to make the string follow the RPN.
For example, xx* need 0 operation to follow RPN since it already follows RPN.
x*x needs two operations to become xx* which follows RPN.
*xx* needs one operation to become xx* which follows RPN.
Your algorithm should work for a string of size up to 100.
Develop a program to demonstrate your implementation of a CSV parsing framework which can be used to generically parse given CSV file into Java beans and prints out information about parsed objects using toString(). The program should follow OOAD open-closed principle to avoid/minimize modification of code when new types are added in future.
You should accept input from STDIN and print the output to STDOUT.
Assume following input format and study sample inputs given below:
Data-type
Header-Row
Data-Row-1
Data-Row-2
....
Data-Row-N
The first line indicates the entity type, 2nd line is comma separate list of column names, 3rd line onwards is the comma separated data values.
Test Case 1 Input
Type:Employee
name,age,salary
Ashok,36,20000
Kishor,30,15000
Bharath,25,30000
Expected Output
Name : Ashok;Age : 36
Name : Kishor;Age : 30
Name : Bharath;Age : 25
Test Case 2 Input
Type:Department
code,name
acc,accounts
prl,payroll
Expected Output
Code : acc;Name : accounts
Code : prl;Name : payroll
Your solution should parse the input into Java Beans (POJOs). For example, in test case 1, you will be make use of following Java bean (if you chose Java as programming language, and equivalent if you were using other language).
class Employee {
private String name;
private int age;
private int salary;
public Employee() {
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
public void setAge(int age) {
this.age = age;
}
public int getAge() {
return this.age;
}
public void setSalary(int salary) {
this.salary = salary;
}
public int getSalary() {
return this.salary;
}
public String toString() {
return "Name : " + this.name + ";" + "Age : " + this.age;
}
}
You can create a similar bean for Department as required for test case 2.
An array is given like {3,6,10,4,5,7,8}. Pick any two number suppose 10 and then 7, as 10 >7, it's an inversion, now if you choose 3 & 5, 3<5, it's not an inversion.
So you have to write a program to calculate total no of such inversion, in a given array. You can use extra space of O(n).
Given an Array, replace each element in the Array with its Next Element(To its RHS) which is Larger than it. If no such element exists, then no need to replace.
Ex:
i/p: {2,12,8,6,5,1,2,10,3,2}
o/p:{12,12,10,10,10,2,10,10,3,2}
One of the questions in one of the interviews -
Given a stack S and another empty stack T and a variable v, write a function that returns S but with its elements reversed.
N jobs are given, their dependency list is given how will you schedule them ?
n jobs are given , their dependency list is given how will you schedule them ?
WAP to modify the array such that arr[I] = arr[arr[I]].
Do this in place i.e. with out using additional memory.
example : if a = {2,3,1,0}
o/p = a = {1,0,3,2}
Note : The array contains 0 to n-1 integers.
Stooge sort implementation using Iteration?
Give a N*N matrix, print it out diagonally.
Follow up, if it is a M*N matrix, how to print it out.
Example:
1 2 3
4 5 6
7 8 9
print:
1
2 4
3 5 7
6 8
9
This is the question in the phone interview.
Please share more questions.
There is a dictionary of billion words and there is one method provided
String getWord(int index); We can give it index and it will return the String on that index .
Now word is given to us we have to find out its index. O(logn) solution was required.
Frog can jump 1 or 2 steps write the code to find out number of ways to go up to n steps
program to pruning a binary tree
Program to check whether undirected graph is a tree or not?
You are given an array with numbers - [11, 3, 11, 11, 3, 2, 0, -2, 2]
You are supposed to write a function that returns the number that appears "odd" number of times.
The solution is obviously using HashMap. But that takes O(n) to create the HashMap and O(n) to lookup. How can one eliminate the second O(n) yet keeping the HashMap?
Hint: Do you really need to count frequency of occurrence of each digit?
Given a linked list where apart from the next pointer, every node also has a pointer named random which can point to any other node in the linked list. Make a copy of the linked list.
Microsoft Excel numbers cells as 1...26 and after that AA, AB.... AAA, AAB...ZZZ and so on.
Given a number, convert it to that format and vice versa.
Design question: Say you have hacked in to a network and can deploy your bot thousands of machines, how would you design your bot so that all the machines work together to download a website, say wikipedia. There should be load balancing and a page should be queryable given its URL.
Given a matrix of letters and a word, check if the word is present in the matrix. E,g., suppose matrix is:
a b c d e f
z n a b c f
f g f a b c
and given word is fnz, it is present. However, gng is not since you would be repeating g twice.
You can move in all the 8 directions around an element.
Given a matrix consisting of 0's and 1's, find the largest connected component consisting of 1's.
Given two arrays of sorted integers, merge them keeping in mind that there might be common elements in the arrays and that common elements must only appear once in the merged array.
Inorder traversal of binary tree
You are given points of 2D plane and an integer n, return n number of points close to origin (0,0)
Given a string, return the string with the words reversed
"I am good" -> "good am I"
List test cases and if you were crunched on time and only had time to test one test case, which would you pick
Design a musical jukebox using object-oriented principles
Construct an iterator of iterator
Here is the below question format:
// E next();
// Boolean hasNext();
// input: Iterator<Iterator<E>>
// output: Iterator<E>
// [[1], [2, 3]] => [1, 2, 3]
Word Search: Given an NxN grid of characters and a word to find, find all instances of that word and print out a list of the coordinates of each character in the word.
What are the different ways of sorting the arrays in Java which is other than Arrays.sort(a1)
Write down the top ten testcases for sanity check of Templerun app in android based mobile. Testcases should appear in priority order?
5ruppes,1rupees,50paisa,25paisa,10paisa,3paisa,2paisa and 1paisa?How many different sums can be formed with the given coins??
If the stored Proc suddenly start running slow ,what will you do??
1>Draw structure of cluster and non cluster index.
2>Fregrementation ,types,how to unfregement
3>When will you go for rebuild and reorginise index.
4>coloumn in (1,2,3,'null',null) what will be the result.
Modify the following code to add a row number for each line is printed
public class Test {
public static void main(String [] args){
printParenthesis(3);
}
public static void printParenthesis(int n){
char buffer[] = new char[n*2];
printP(buffer,0,n,0,0);
}
public static void printP(char buffer[], int index, int n, int open, int close){
if(close == n){
System.out.println(new String(buffer));
}else{
if(open > close){
buffer[index] = ']';
printP(buffer, index+1, n, open, close+1);
}
if(open < n ){
buffer[index] = '[';
printP(buffer,index+1,n,open+1,close);
}
}
}
}Expected Output:
1.[][][]
2.[][[]]
3.[[]][]
4.[[][]]
5.[[[]]]What changes needs to be done to accomplish the output expected?
How many 3-digit numbers can be made using the numbers 1, 2, 3, 4 or 5 such that the even numbers are not repeated?
There are many sorted arrays. Find a minimum range, so that in each array there's at least one integer within this range.
Given a normal binary tree, write a function to serialize the tree into a string representation (returning the string), and also a function to deserialize a serialized string into the original binary tree.
Given a normal binary tree, write a function to serialize it into a string representation (returning a string), and also a function to deserialize the string into the original binary tree
A professor wants to see if two students have cheated when writing a paper. Design a function : hasCheated(String s1,String s2, int N) that evaluates to true if two strings have a common substring of length N. Additional question after implementation. Assume you don't have the possibility of using String.contains() and String.substring(). How would you implement this?
Given a list of 4 billion integers, find an integer not in the list using 4MB of memory. (interview was in Java)
Write atof in Java, which converts a string representation of a float (like "342.18E-10") to an actual float without using any built-in parsing functions.
N*N matrix is given with input red or black. You can move horizontally, vertically or diagonally. If 3 consecutive same color found, that color will get 1 point. So if 4 red are vertically then point is 2. Find the winner.
Find the kth largest node in an unsorted linked list. ( Is quick select (selection algorithm) applicable on linked list (not array?)
Suppose you have a collection of collection
Eg : CEO-> Vps-> GMs ->..
CEO will contain collection of VP's, VP's will have collection of GM's and so on.
Suppose you need to find a particular GM is the alias is given. Write a linq query to get the employee details if the employee alias is given.
Hint : Use Recursion + Linq
Given an array of (unsorted) integers, arrange them such that a < b > c < d > e... etc.
Suppose you have a collection of collection
Eg : CEO-> Vps-> GMs ->..
CEO will contain collection of VP's, VP's will have collection of GM's and so on.
Suppose you need to find a particular GM is the alias is given. Write a linq query to get the employee details if the employee alias is given.
Hint : Use Recursion + Linq
Make a JAVA program for an array of classes.
class should have 4 or 5 attribute and Array should contain 10 data which all have that 4 or 5 attribute of class. And Retrieve each attribute from all data. (Like Array of structure in C).
Check if two binary search tree have the same in-order traversal in O(1) space
Given an array of integers and a length L, find a sub-array of length L such that the products of all integers are the biggest.
Example:
Input: {4, 1, -7, -8, 9}, 3
Output: {-7,-8,9}
Find the presence of a given word in a given grid, word can be matched in any direction up-down, down-up, left-right, right-left, both diagonals up and down etc.
While playing NFS most wanted on a desktop, the application crashes.
Debug the scenario?
A Desktop Java application which was working till yesterday crashes today --- no help from Java debugger. How do u go about debugging this?
VLC player installable is crashing. Debug
Given a number in an array form, Come up with an algorithm to push all the zeros to the end.
Expectation : O(n) solution
Test Google advertisements.
Basically the expectation is to get the requirement, assume certain things and come up with test strategies.
E.g : UI, Backend, Compatibility, Accessibility etc.
On the fly question were asked
Give 2 arrays of size 7 and 3 which are sorted such that the last 3 blocks in first array are empty, merge the arrays in a sorted manner in the most efficient way.
E.g:-
a[7] = [4, 10, 11, 20__, __, __]
b[3] = [1,3,7]
Was asked to explain Current QA and roles in detail. How was automation implemented and basis of the same?
Question 2) Implement insert and delete in a tri-nary tree. A tri-nary tree is much like a binary
tree but with three child nodes for each parent instead of two -- with the left node being values
less than the parent, the right node values greater than the parent, and the middle nodes values
equal to the parent.
For example, suppose I added the following nodes to the tree in this order: 5, 4, 9, 5, 7, 2, 2.
The resulting tree would look like this:
5
/ | \
4 5 9
/ /
2 7
|
2
Design a download manager. The download manager would be shipped with a browser. Detailed design of components and interaction between them.
Follow up question - What features would you add to the download manager so that it is more marketable than others.
Write a function in C to create a new BST which is the mirror image of a given tree.
Consider the statement
result = a ? b : c;
Implement the above statement without using any conditional statements.
Write a multi threaded C code with one thread printing all even numbers and the other all odd numbers. The output should always be in sequence
ie. 0,1,2,3,4....etc
Write a piece of code to find out if the system is x86 architecure of Sparc
Find a shortest path in a N*N matrix maze from (0,0) to (N,N), assume 1 is passable, 0 is not, 3 is destination, use memorization to cache the result. Here is my code. I am not sure if I am caching it right.
public static class MazeResult {
public boolean solved;
public List<String> res = new ArrayList<String>();
public int steps = Integer.MAX_VALUE;
public MazeResult(boolean isSolved) {
solved = isSolved;
}
}
static Map<String, MazeResult> cache = new HashMap<String, MazeResult>();
static MazeResult solveMaze(int[][] m, int r, int c, List<String> path, HashSet<String> visited) {
if (r < 0 || r >= m.length || c < 0 || c >= m[0].length)
return new MazeResult(false);
String cell = r + "" + c + "";
if (m[r][c]==0 || visited.contains(cell))
return new MazeResult(false);
if (m[r][c] == 3) {
MazeResult ret = new MazeResult(true);
ret.res = new ArrayList<String>(path);
ret.res.add(cell);
ret.steps = path.size() + 1;
return ret;
}
if (cache.containsKey(cell))
return cache.get(cell);
path.add(cell);
visited.add(cell);
MazeResult ret = new MazeResult(false), temp = new MazeResult(false);
temp = solveMaze(m, r, c+1, path, visited);
compareResult(temp, ret);
temp = solveMaze(m, r, c-1, path, visited);
compareResult(temp, ret);
temp = solveMaze(m, r+1, c, path, visited);
compareResult(temp, ret);
temp = solveMaze(m, r-1, c, path, visited);
compareResult(temp, ret);
path.remove(path.size()-1);
visited.remove(cell);
cache.put(cell, ret);
return ret;
}
private static void compareResult(MazeResult temp, MazeResult ret) {
if (temp.solved) {
if (temp.steps < ret.steps) {
ret.res = temp.res;
ret.steps = temp.steps;
}
ret.solved = true;
}
}Flatten an iterator of iterators in Java. If the input is [ [1,2], [3,[4,5]], 6], it should return [1,2,3,4,5,6]. Implement hasNext() and next(). Note that the inner iterator or list might be empty.
Flatten an iterator of iterators in Java. If the input is [ [1,2], [3,[4,5]], 6], it should return [1,2,3,4,5,6]. Implement hasNext() and next().
Suppose you get number of unique users every second from bing
For eg, 2,4,5,1,2,etc
You need to write a web service method , such that it takes the input n, which return lowest n unique number from the list of unique numbers. For eg, if n is 3 then you need to return 2,1,2
A draw method is given, write a function to draw a chess board. The Draw method, draws a square and has parameters row position, column position and color.
Given a linked list like a1-a2-a3-a4-b1-b2-b3-b4. Convert it into a1-b1-a2-b2-a3-b3-a4-b4.
Given a m*n matrix representing a maze wherein some of the positions are not reachable, find all paths from (0,0) to (m,n) using dynamic programming
Given array of N integers ranging from 0 to N-1. Output maximum repeating integer. Use only O(1) memory.
Given a Binary Tree (balanced or not) write a method that transforms the tree in a degenerate tree (basically a data structure like a sorted linked list where each node has the left child null) and returns the new root. This must be made in place, no external memory usage is allowed.
Given a set of intervals, find the interval which has the maximum number of intersections (not the length of a particular intersection). So if input (1,6) (2,3) (4,11), (1,6) should be returned. Some suggest to use Interval Tree to get this done in O(logn), but I did not understand how to construct and use the Interval Tree after reading its wiki page. Is there any other way to do it? If Interval tree is the only option, please educate me how to construct/use one. Thanks.
(17) A museum is selling tickets to a fundraiser. As people place orders, their customer IDs are appended to a linked list. Due to an error, too many tickets have been sold and the unfortunate customers must now be notified that they cannot purchase a ticket after all. Given the list and the number of customers to notify (k), return the node in the list for the first customer that needs to be notified. An optimal solution will not use any additional data structures. You may assume k is less than the number of nodes in the list. You may use the JDK or the standard template library. Your solution will be evaluated on correctness, runtime complexity (big-O), and adherence to coding best practices. A complete answer will include the following:
Document your assumptions
Explain your approach and how you intend to solve the problem
Provide code comments where applicable
Explain the big-O run time complexity of your solution. Justify your answer.
Identify any additional data structures you used and justify why you used them.
Only provide your best answer to each part of the question.
Example:
Input: myList: 1 -> 8 -> 4 -> 2 -> 7 -> 13 -> 3 k: 2
Output: 13 -> 3
Use one of the following skeletons for your solutions:
Java:
public classCustomerTracking
{ publicstatic class ListNode
{ publicint customerId;
publicListNode next; }
public staticListNode customersToNotify (ListNode myList, int k) { } }
/**
* Returns a^b, as the standard mathematical exponentiation function
*/
public double pow(double a, int b) {}
Interviewer looking for log(n) solution, right on first attempt.
/**
* Given a nested list of integers, returns the sum of all integers in the list weighted by their depth
* For example, given the list {{1,1},2,{1,1}} the function should return 10 (four 1's at depth 2, one 2 at depth 1)
* Given the list {1,{4,{6}}} the function should return 27 (one 1 at depth 1, one 4 at depth 2, one 6 at depth2)
*/
/**
* This is the interface that represents nested lists.
* You should not implement it, or speculate about its implementation.
*/
public interface NestedInteger
{
// Returns true if this NestedInteger holds a single integer, rather than a nested list
public boolean isInteger();
// Returns the single integer that this NestedInteger holds, if it holds a single integer
// Returns null if this NestedInteger holds a nested list
public Integer getInteger();
// Returns the nested list that this NestedInteger holds, if it holds a nested list
// Returns null if this NestedInteger holds a single integer
public List<NestedInteger> getList();
}
In Amazon's interview, Round 2 they asked question:
Write a program to print inorder traversal of two trees.
Both values must be printed alternatively.
e.g. if inorder traversal of tree 1 is 10, 15, 20 and tree 2 is 100, 150, 200 then it should print
10, 100, 15, 150, 20, 200.
I tried printing it recursively by calling 2 functions recursively (f1 calls f2, then f2 calls f1 and so on).
I don't know where my approach is going wrong? I know there are other ways to do it as well but in this approach what is the mistake?
public class HelloWorld{
//this is the Node used in the tree
static class Node{
private int data;
private Node left;
private Node right;
public Node(int data){
this.data = data;
left = null;
right = null;
}
public void setLeft(Node left){
this.left = left;
}
public void setRight(Node right){
this.right = right;
}
public Node getLeft(){
return this.left;
}
public Node getRight(){
return this.right;
}
public int getData(){
return this.data;
}
public boolean equals(Node n){
if(this.data ==(int) n.getData()) return true;
else
return false;
}
}
public static void main(String[] args){
HelloWorld bts = new HelloWorld();
bts.run();
}
//execute the test case
public void run(){
Node root = new Node(10);
insert(root,new Node(20));
insert(root,new Node(50));
insert(root,new Node(40));
insert(root,new Node(15));
Node node2 = new Node(100);
insert(node2,new Node(200));
insert(node2,new Node(500));
insert(node2,new Node(400));
insert(node2,new Node(150));
//inOrderTraverse(node2);
inOrderTraverse1(root, node2);
}
// insert a node to the binary search tree
public void insert(Node root, Node n){
if(root == null|| n == null) return;
if(root.getData() > n.getData()){
if(root.getLeft() == null){
root.setLeft(n);
}else{
insert(root.getLeft(),n);
}
}else if(root.getData() < n.getData()){
if(root.getRight() == null){
root.setRight(n);
}else{
insert(root.getRight(),n);
}
}
}
public void inOrderTraverse(Node node){
if(node != null){
if(node.getLeft() != null)
inOrderTraverse(node.getLeft());
System.out.print(" "+node.getData());
if(node.getRight() != null)
inOrderTraverse(node.getRight());
}
}
//in-order Traversal
public void inOrderTraverse1(Node node1, Node node2){
if(node2 != null){
inOrderTraverse2(node1, node2.getLeft());
System.out.println(" "+node2.getData());
inOrderTraverse2(node1, node2.getRight());
}
}
public void inOrderTraverse2(Node node1, Node node2){
if(node1 != null ){
inOrderTraverse1(node1.getLeft(), node2);
System.out.println(" "+node1.getData());
inOrderTraverse1(node1.getRight(), node2);
}
}They have given some flowchat questions in thought works ... how to solve these questions can anybody explain for all the questions....?
http://placement.freshersworld.com/placement-papers/ThoughtWorks/Placement-Paper-Whole-Testpaper-29732
Make a Java/C program that takes n as input and gives you all sequence of n by using recurssion. For example if n=3, output will be:
111
112
113
121
.........
........
331
332
333.
Idea student
I idea student for facebook.
5ruppes,1rupees,50paisa,25paisa,10paisa,3paisa,2paisa and 1paisa?How many different sums can be formed with the given coins??
Given an array, print all the pairs that sum to a particular value. You are not given the value, find all possible values and print pairs for them
For an N-ary Tree find the nearest common ancestor.
Given: rootid and a function which finds and returns the immediate parent of a node.
For an N-ary Tree find the nearest common ancestor.
Given: rootid and a function to find the immediate parent of a node.
What happens when you type a link in any browser and click GO button? List all steps.
What should be the issue if the browser app build that i have today is 1 second 250 milliseconds slower than yesterday's build? ASSUME: WiFi is perfect, loading 10 webpages from a controlled server - hence there are no infrastructure or server side delays causing this.
What would you think might be the issue? How would you debug?
You are given a string FOOFIGHTERS. You have to come up with an algorithm that will compress this string.
You also have to make sure that you are not using extra memory. For example: FOOFIGHTERS will be compressed as FO2FIGHTERS. You should not use another array or bitfield to keep a frequency count for the individual letters.
Find out the complexity of the code............
Fib[n]
if(n==0) then retun0;
else if(n==1) then retun1
else return Fib[n-1]+Fib[n-2].please give simler way..........
Given:
R number of Red Cards
B number of Black cards
K
Cards needs to be placed in a circle. Start from a position and for every K moves remove that card And repeat the process until all the cards are eliminated.
Question: Position the cards such that the red cards are completely eliminated before the blacks cards are selected for elimination.
Given a timer time() with nanosecond accuracy and given the interface
interface RealTimeCounter:
void increment()
int getCountInLastSecond()
int getCountInLastMinute()
int getCountInLastHour()
int getCountInLastDay()
implement the interface. The getCountInLastX functions should return the number of times increment was called in the last X.
Given a list of pairs (a,b) where a is the number of a node and b is its parent, construct a tree and return the root.
Given a set of Lego bricks of height 1, 2, 3, and 4, each colored differently, write a program to compute the number of ways of constructing a tower of height n≥1.
Create a data structure that has fast insertion, removal, membership testing, and random selection.
You have two anagram strings S and P. You can do an operation swap(), which swaps two adjacent characters in a string, or swaps the last character and the first character in a string. What is the minimum number of operations you have to perform to change S to P.
E.g. S = "abcd", P = "bdca", the output should be 2, as "abcd" -> "dbca" -> "bdca".
Write code to find the next least node in a binary search tree given a node?
Given N numbers , [N<=10^5] we need to count the total pairs of numbers that have a difference of K. [K>0 and K<1e9]
Input Format:
1st line contains N & K (integers).
2nd line contains N numbers of the set. All the N numbers are assured to be distinct.
Output Format:
One integer saying the no of pairs of numbers that have a diff K.
Sample Input #00:
5 2
1 5 3 4 2
Sample Output #00:
3
Sample Input #01:
10 1
363374326 364147530 61825163 1073065718 1281246024 1399469912 428047635 491595254 879792181 1069262793
Sample Output #01:
0
Note: Java/C# code should be in a class named "Solution"
Read input from STDIN and write output to STDOUT.
Given a string, print the character which appears the maximum number of times in the string.
The string will contain only ascii characters. If there is a tie in the maximum number
of times a character appears in the string, print the character which appears first in the string.
Notes:
1. The length of the string will be between 1 and 10000, inclusive.
2. Make sure you don't print anything other than a single character in the function. Otherwise, your solution will be marked wrong.
3. You only need to complete the function printMaximumOccurringCharacter.
Sample Input #00
helloworld
Sample Output #00
l
Sample Input #01
aabbccddeeffgghhiijjkkllmmnnooppqqrrssttuuvvwwxxyyzz
Sample Output #01
a
Sample Input #02
abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz
Sample Output #02
a
4.
.There is an infinite integer grid at which N people have their houses on. They decide to unite at
a common meeting place, which is someone's house.
From any given cell, all 8 adjacent cells are reachable in 1 unit of time.
eg: (x,y) can be reached from (x-1,y+1) in a single unit of time.
Find a common meeting place which minimises the sum of the travel times of all the persons.
Input Format:
N
The following N lines will contain two integers saying the x & y coordinate of the i-th person.
Output Format:
M M = min sum of all travel times;
Constraints:
N <= 10^5
The absolute value of each co-ordinate in the input will be atmost 109
HINT: Please use long long 64-bit integers;
Input #00:
4
0 1
2 5
3 1
4 0
Output #00:
8
Explanation: Sums of travel times of the houses are 11, 13, 8 and 10. 8 is the minimum.
Input #01:
6
12 -14
-3 3
-14 7
-14 -3
2 -12
-1 -6
Output #01:
What are the screen dimensions of various iPhone models?
What is the screen dimensions of various iPhone models?
why do you choose Amazon?
You are given an unsorted array of integers that contain duplicate numbers.
Only one number is duplicated odd number of duplications, other numbers are repeated even number of duplications.
Find this number.
Write code to find the next least node in a binary search tree given a node
Write code to find the next least node in a binary search tree given a node?
Find the k-th Smallest Element in Two Sorted Arrays. I followed the algorithm from this post, http://leetcode.com/2011/01/find-k-th-smallest-element-in-union-of.html
But it does not handle the case where there are duplicates? Does anyone know how to do that? Also, in Java, how should we reduce the size of the arrays? I used the code below, but did not work.
public static int kthSmallest2(int[] a, int[] b, int k, int a_left, int a_right
, int b_left, int b_right) {
if (a_left==a_right)
return b[k-1];
else if (b_left==b_right)
return a[k-1];
int m = a_right-a_left, n=b_right-b_left;
int i = (int)((double)m / (m+n) * (k-1)); // i can be any number
// make sure i + j = k - 1
// int i = (a_left+a_right)/2 + k/2; // i can be any number
int j = k - 1 - i;
int bj_1 = 0, ai_1 = 0;
if (i==0) { ai_1 = Integer.MIN_VALUE; } // in case i = 0, outOfBound
else { ai_1 = a[i-1]; }
if (j==0) { bj_1 = Integer.MIN_VALUE; } // in case j = 0, outOfBound
else { bj_1 = b[j-1]; }
if (bj_1 < a[i] && a[i] < b[j]) // kth smallest found, b[j-1] < a[i] < b[j]
return a[i];
if (ai_1 < b[j] && b[j] < a[i]) // kth smallest found, a[i-1] < b[j] < a[i]
return b[j];
if ( a[i] < b[j] ) // if true, exclude a's lower bound (if 2 arrays merged, a's lower bound must
// reside before kth smallest, so also update k.
// also exclude b's upper bound, since they are all greater than kth element.
return kthSmallest2(a, b, k, i+1, a.length-1, 0,j-1);
else
return kthSmallest2(a, b, k, 0, i-1, j+1, b.length-1);
}Given a bunch of floors....and egg will break only if it is thrown from a floor and any floor above that....what least number of eggs u would need if total floors are say 32..
I went with binary search..where I strt from middle...throw the egg, if it doesnt break...
go to middle of upper half and if it does break..i know I should go to middle of lower half.
a Bunch of devices....u can share files etc.,..each device might support only some limited
format of files. A common server hosting all the files repository.
If every leaf node in binary tree forms a double linked list...that is
all the leaf nodes for a DLL.
ex:
1
/ \
2 3
/ \ / \
4 ......5....6.......7
.........................
print all the leaf nodes....
This involves first identifying leaf node. We can do that by checking at every node, if the its child points right back at the parent..then parent is leaf node.
After this it is simple traverssal of DLL and printing nodes.
Level order traversal.
Mirror image of tree
Ancestor in binary tree.
First round
Given set of coins of different denominations....
like 1$ (100)....5$(50)...etc., and given an amount..I was asked to come up with optimal solution
using least number of coins to get that amount.
I told greedy approach of starting wiht maximum denomination coin..use up as much as possible...then moving on to next..I was asked to tell dynamic programming approach...
..I told I will split the amount in half..and keep doing it until i reach 1 1 ..combination..start calculating optimal combination..and keep going up like ...
Next question was to try and implement google autosuggest...I told i will use tries...pseduo code and some optimizations on top of it.
Find top K(1000) strings that occur frequently from a file having some billions of strings.
Given a list of 'N' coins, their values being in an array A[], return the minimum number of coins required to sum to 'S'
Given a BST, replace each node with the sum of the values of all the nodes that are greater than that node. Only constraint being that I was not allowed to use any global or static variable.
Design a meeting scheduler. The solution I came up with was to create an array of intervals for each day, so if intervals is 15 mins, then array size would be 24*4. However, if interval is small, that will substantially increase the size of the array, and that might be considered as a waste of space, though it supports O(1) look up. I was wondering if there is any other way to do this. I think we might be able to keep a sorted array of meetings sorted by start time, so look up would be O(logn). But insertion in the middle of the array would take O(n) since it requires data shifting.
public interface Permutations {
/**
* Generate all permutations of given sequence of elements.
* Return a list of all distinct permutations.
*
* E.g.
* generate([1, 2, 3]) -> [1, 2, 3], [1, 3, 2], [2, 3, 1], [2, 1, 3], [3, 1, 2], [3, 2, 1]
*/
vector<vector<int>> generate(vector<int> items);
}
public interface InfluencerFinder {
/**
* Given a matrix of following between N LinkedIn users (with ids from 0 to N-1):
* followingMatrix[i][j] == true iff user i is following user j
* thus followingMatrix[i][j] doesn't imply followingMatrix[j][i].
* Let's also agree that followingMatrix[i][i] == false
*
* Influencer is a user who is:
* - followed by everyone else and
* - not following anyone himself
*
* This method should find an Influencer by a given matrix of following,
* or return -1 if there is no Influencer in this group.
*/
int getInfluencer(boolean[][] followingMatrix)
// cat, actor -> T
// car, actor -> F
bool anaStrStr (string needle, string haystack)
{
}Write a function that takes 2 strings , search returns true if any anagram of string1(needle) is present in string2(haystack)
what is the use using 8 GB RAM in Operating System if we can manage a process with 2 GB RAM in 32 bit and 64 bit Operating System.
Design a meeting scheduler. One way is to use an array to represent each interval, like every 15 mins. Although it provides O(1) look up, if interval is small, it seems like we are wasting a lot of space. Any alternative approach that can save space? If we keep a sorted array of meetings sorted by start time, look up will be O(logn), but inserting the new meeting in the middle of the array will require shifting elements, which is O(n).
Given a binary tree, convert it into another binary tree whose in-order representation would have its elements listed in sorted order
Given a binary search tree of n nodes, find all the pair of nodes whose sum is equal to a given number k in O(n) time and constant space.(algo+code)
Rotate a 2-D Matrix by 90 degrees
Print all the cycles in a directed graph
Given n, find the smallest number for which product of the digits is n, if no such number exists, print -1
Given an array of integers (+ve and -ve), give a contiguous set of numbers that add to 1
Eg. 4 3 5 -3 -1 2 -3 10 2
Ans: 5 -3 -1 2 -3
Finding a pair of elements from two sorted lists(or array) for which the sum of the elements is a certain value. Anyway solution that can do better than O(a.length + b.length)?
I/P: N, k
O/P: all subset of N with exactly K elements.
eg: I/p: N = 5, K =3
O/p:
1 2 3
1 2 4
1 2 5
1 3 4
1 3 5
2 3 4
2 3 5
3 4 5
There is an array {1,2,3,4,5,6,7,8}
Divide the array in two subarrays such that the difference between sum of the elements of individual subarrays is minimum.
lets say u divide the arrays in a1 and a2.
Then sum of elements of a1 - sum of elements of a2 should be minimum if u divide the array in other way possible.
Given a Input Matrix of NXN . Print the matrix after mirroring on its primary diagonal
if Input is 1,2,3,4,5.6,7,8,9
Output is 1,4,7,2,5,8,3,6,9
There is a string , where a character is missing.Print the missing character.The range is present in the string and the characters are case sensitive.
For example:-If input is "baADfc".
Here the range is a to f.
The missing character to be printed is e.
.
One of the many ways of representing a tree is to have an array(of length same as number of nodes), where each element in the node denotes the parent of that node.
Eg -
{-1, 0, 0, 1, 1} would represent a tree with -
* 0 as root
* 1 and 2 as children of 0
* 3 and 4 as children of 1
Given a similar representation, you have to print reverse level order traversal of the corresponding tree.
Level order traversal of a tree is where we traverse levels of tree one by one.
Eg -
For the above given tree, level order traversal would be -
0
1 2
3 4
And hence, the reverse level order traversal is -
3 4
1 2
0
Please note -
* An element with parent = -1 is the root element.
* An element with the least index becomes the left most child. (ie. a node with always be on left of all its siblings that have higher index than it)
* When printing a level of tree you need to maintain left to right order.
Input Format -
First line of the input contains number of nodes in the tree (N)
Next line contains N (space seperated) numbers that denote where i-th number will denote the parent node of i-th node.
Output Format -
Print reverse level order traversal of the corresponding tree, with every new level starting in a different line.
Notes/Limits -
* 1 <= N <= 50
* There will be only one root element in any given test case
* Given numbers will always form a valid undivided tree
* Output should be in the exact format as specified (including whitespaces)
Sample Test Cases -
Input -
5
-1 0 0 2 1
Output -
4 3
1 2
0
Input -
9
8 7 0 5 5 8 7 0 -1
Output -
1 6
2 7 3 4
0 5
8
Input -
45
24 42 4 30 29 43 22 15 26 36 26 16 3 22 21 41 18 16 34 41 12 29 32 30 43 15 4 38 36 -1 24 42 18 6 21 38 6 17 32 17 3
34 12 14 14
Output -
1 31
20 42 9 28
12 40 33 36
3 23 37 39 6 13 27 35
0 30 11 17 22 38 7 25
5 24 16 32 15 19
8 10 43 44 18 41
2 26 14 34
4 21
29
Input -
33
17 25 0 14 7 2 5 25 18 8 16 27 10 9 19 7 31 31 19 0 8 14 9 17 18 2 30 16 30 10 5 -1 27
Output -
13 22
26 28 4 15 9 20
6 30 1 7 3 21 8 24
5 25 14 18
12 29 11 32 2 19
10 27 0 23
16 17
31
Basically I know that 378 small sheets were printed. These came from 21 full sized sheets of paper. The large sheets of paper were torn, leaving rough edges that can be put re-joined digitally. I have now recorded 60 different sheets, and have joined only five pairs. What I would like to know is what is the likely number of sheets that the five pairs came from of the 21 originally used.
Design a dialpad for a cellphone in a language which does not have conditional statements.
Design a dialpad for a cellphone in a language which does not have conditional statements.
Design a dialpad for a cellphone in a language which does not have conditional statements.
How would you convert a program that runs on a little endian machine to work on big endian
How would you convert a program that runs on a little endian machine to work on big endian
How can you implement oops features in C?
we have a random list of people. each person knows his own height and the number of tall people in front of him. write a code to make the equivalent queue.
for example :
input: <"Height","NumberOfTall","Name">,
<6,2,"A">,<1,4,"B">,<11,0,"C">,<5,1,"D">,<10,0,"E">,<4,0,"F">
output: "F","E","D","C","B","A" --> end of queue
Giving a number T, print out all possible ways to get to T.
For example
T= 5
1 + 1 + 1 +1 +1
2 + 1 + 1 + 1
3 + 1 +1
2 + 2 + 1
4 + 1
3 + 3
Note that, 3 + 2 is equal than 2 + 3, so you don´t have to print both cases.
What is the time complexity? ( VERY IMPORTANT TO ELABORATE ) Brute force is not allow.
Given a set of integer dots (like (1,5)), how can you find a pair that has an integer mid-point? For example, (1,1) and (3,3) have an integer mid-point of (2,2), while (1,1) and (3,2) do not. Tell the complexity of your code. What if the dots are N-dimensional?
Write a function which checks a Red-Black-Tree that the max depth isn't > than 2* min depth. It must return a boolean.
boolean checkdepth(){}
no class variables
Shopkeeper want sells in the packs of 20,9 and 6. Given an n, you need to find whether its possible to buy the items or not.For example n=21, you can buy 2 packs of 6 and one pack of 9(2*6 + 9)
Output 1 if possible and 0 if not
Test cases:
1) n=47 ==> possible, output = 1
2) n=7 ===> not possible, output = 0
#include <iostream>
using namespace std;
class A
{
int x;
public:
A() { cout << "A's constructor called " << endl; }
};
class B
{
static A a;
public:
B() { cout << "B's constructor called " << endl; }
static A getA() { return a; }
};
A B::a; // definition of a
int main()
{
B b1, b2, b3;
A a1 = b1.getA();
return 0;
}
in the above prog the output is
A's constructor called
B's constructor called
B's constructor called
B's constructor called
the all 4 lines belongs to before the 2nd line in main
my question is that ,in the 2nd line in main, A's constructor is called or not?
if not then why?
Given a string, rearrange the string to a palindrome and return the palindrome if present or -1
Example:
i/p
abb
ab
o/p
bab
-1
Find first unique number in an unsorted array of 32 bit numbers without using hash tables or array of counters.
There is a large data file with 10 digit numbers. You are allowed to use only 20 megabytes of memory. How would you sort them ?
Find the longest repeating character in a sorted string
Suppose that you been offered the opportunity to invest in the Volatile Chemical
Corporation. Like the chemicals the company produces, the stock price of the
Volatile Chemical Corporation is rather volatile. You are allowed to buy one unit
of stock only one time and then sell it at a later date, buying and selling after the
close of trading for the day. To compensate for this restriction, you are allowed to
learn what the price of the stock will be in the future. Your goal is to maximize
your profit.
Day 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
Price 100 113 110 85 105 102 86 63 81 101 94 106 101 79 94 90 97
Change 0 13 -3 - 25 20 -3 -16 -23 18 20 -7 12 -5 -22 15 -4 7find the subset of days where the profit is the highest.
What is the time complexity?
void state1(string st)
{
for (int i = 0; i < st.Length; i++)
{
if (st[i] == 's')
{
i++;
state2(st);
}
}
public void state2(string st[i])
{
if (st[i] == 'e')
?????????
}
in main
{
state1(str); // we are taking dynamically a string and passing. how will we pass incremented index to 2nd function????????/
}
Serling Enterprises buys long steel roads and cuts them into shorter rods, which it then sells. Each cut is free. The management of Serling Enterprises charges for a road of length i inches. Road lengths are always an integral number of inches.
The rod-cutting problem is the following: Given a rod of length n and a table of prices V for {1,2...n} determine the maximum revenue Rn obtain by cutting up the road and selling the pieces.
Table:
length i 1, 2, 3 ,4 ,5 , 6 , 7 , 8 , 9, 10
price Pi 1, 5, 8, 9, 10,17,17,20,24,30Write a routine to reverse every k nodes in a given linked list without using additonal memory.
input : 1,2,3,4,5,6 k:3
output : 3,2,1,6,5,4
Write a routine to reverse every k nodes in a given linked list
input : 1,2,3,4,5,6 k:3
output : 3,2,1,6,5,4
Find all nodes that are at a distance k from leaf nodes
if you are given 2 arrays
one has n elements and another has n+2 elements
and the elements in the array are same except the 2 elements
find those two extra elements..
give the optimal solution.
Print all palindromes of size greater than equal to 3 of a given string. (DP)
given an 2D matrix M, is filled either using X or O, you need to find the region which is filled by O and surrounded by X
and fill it with X.
example 1:
X X X X X
X X O O X
X X O O X
O X X X X
Answer :
X X X X X
X X X X X
X X X X X
O X X X X
example 2:
X X X X X
X X O O X
X X O O O
O X X X X
answer 2:
X X X X X
X X O O X
X X O O O
O X X X X
Explain the output of the following code:
int main( )
{
int x = 10, y = 20;/.
x =!x;
y =!x&&!y;
printf(“x =%d y =%d”, x, y);
return 0;
}Given an array of n elements (a1,a2,..ai,...,an). You are allow to chose any index i and j, such that (i!=j) and allow to perform increment operation on ai = ai+1 and decrements operation on aj = aj - 1 infinite number of times. How many maximum number of elements you can find that have same number.
example 1:
1 4 1
ans: 3
example 2:
2 1
ans : 1
Given an array of n elements (a1,a2,..ai,...,an). You can allow to chose any index i and j, such that (i!=j) and allow to perform
increment operation on ai = ai+1 and decrement operation on aj = aj-1 infinite number of times.
How many number of elements you can find which have same numbers.
example 1:
1 4 1
ans: 3
example 2:
2 1
ans : 1
Given a number N, find the smallest 3 digits number such that product of its digits is equal to N.For example for N=100 , 3 digits number is 455.
Given a function “f” in which 0 occurs with probability 0.4 and 1 occurs with probability 0.6. Using function “f” deduce a new function “f1” such that both 0 and 1 occurs with probability 0.5
Write an application in Java to simulate file system. For e.g. implement commands: ls -l (list contents of director sorted by name), cd .. (to go to parent directory), pwd to return the complete path to current directory etc. It was a 2 hour remote programming test.
Your system will have Directory and Files. A directory can contain files and other directories.
Subset Sum
Given a target value and a list of numbers to pick from, pick numbers from the list such that the numbers picked add up to the target value.
For example, if given a target value of 150 and a list of numbers to pick from consisting of 1, 2, 100, 22 and 28, the correct answer would be 100, 22 and 28 because 100 + 22 + 28 =150. If given a target value of 30 and the sample numbers to pick from were 1, 2, 100, 22 and 28, the correct answer would be 28 and 2 because 28 + 2 = 30.
NOTE: Once you use a number from the list you cannot pick it again.
NOTE: If no combination of numbers adds up to the requested value, the correct answer is "No combination matches".
NOTE: There can be more than one correct answer. For example, for target value 3 and list 1, 2 and 3 the correct answer would be either: 1, 2 or 3. You only need to return 1 correct answer not all of them.
Write a program that takes a list of numbers from the command line. The first number is the target value and the reminder of the numbers (however many there may be) is the set of numbers you have to pick from. The program should either output a subset whose sum equals the target or "No combination matches" if no such subset exists. We would prefer you use Java or C# on this program, but you can use another procedural language if you don't know Java or C#.
For example, the following inputs should yield the following results:
SubsetSum 15 1 2 3 5 7 10
{3,7,5}
SubsetSum 9 1 2 3 5 7 10
{2,7}
SubsetSum 100 1 2 3 5 7 10
No combination matches
why will the code show error when tried to compiled
below given is a C program snippet to get height of a binary tree.
int height (struct node * root)
{
if(root=NULL)
return 0;
else
{
return max(height(root->left), height(root->right))+1;
}
}
int max(int a,int b)
{
return ((a>b)?a:b);}
In Java: Write a function in language of your choice that takes in two strings, and returns true if they match. Constraints are as follows: String 1, the text to match to, will be alphabets and digits. String 2, the pattern, will be alphabets, digits, '.' and '*'. '.' means either alphabet or digit will be considered as a "match". "*" means the previous character is repeat 0 or more # of times. For example: Text: Facebook Pattern: F.cebo*k returns true.
Design a parking lot system where you need to provide a token with the parking space number on it to each new entry for the space closest to the entrance.
When someone leave you need update this space as empty.
What data structures will you use to perform the closest empty space tracking, plus finding what all spaces are occupied at a give time.
Design a parking lot system where you need to provide a token with the parking space number on it to each new entry for the space closest to the entrance.
When someone leave you need update this space as empty.
What data structures will you use to perform the closest empty space tracking, plus finding what all space a occupied at a give time.
Find median from a stream of flowing numbers
Write a piece of code to find out if the system is x86 architecure of Sparc
Write a function in C to create a new BST which is the mirror image of a given tree.
Write a multi threaded C code with one thread printing all even numbers and the other all odd numbers. The output should always be in sequence
ie. 0,1,2,3,4....etc
Consider the statement
result = a ? b : c;
Implement the above statement without using any conditional statments.
Write a piece of code to find out if the system is x86 architecture of Sparc
Write multi threaded code in C so that one thread prints all even numbers and other all odd numbers with the output always in sequence ie. 0,1,2,3...etc
Write a piece of code to find out if a system is x86 architecture or Sparc?
Implement a ternary operator without using any condition statements. For example
result = a ? b : c;
Implement the above statement without using ternary or any conditional statements so that result gets b or c depending on value of a. Assume a is either 1 or 0 for simplicity.
write test cases for a game on pc and mobile device and you can play that game on pc and pause it on pc and again resume this game on mobile.
write test area and test case for a pen drive
find whether a number is palindrome or not if number is not palindrome ( i.e 112 ) make it in a palindrome form and check if it is palindrome or not.
Example - 121 this is a palindrome number but 112 is not palindrome so make it 121 and check.
How to perform string matching using suffix tree? (code)
Given a binary search tree of n nodes, find all the pair of nodes whose sum is equal to a given number k in O(n) time and constant space.
what is memory leak and write a shell script to find memory leak ?
What is memory leak and write a shell script to find memory leak ?
This question was a modification of question 1 in this telephonic interview
i/p: Binary Tree
O/p: print all the pairs along a path to leaf nodes, which don't follow BST property.
Eg:-
7
2 19
8 5 12 17
13 21
46
http://pastebin.com/raw.php?i=BqrNz9pu
o/p: (8,2), (8,7)
(13, 5) ( 13, 7)
and soo on.
I/P: chronological order of stock value of a particular company
O/P: Maximum profit when you buy on a day and sell on another day.
Eg:
i/p: 79 14 3 21 104 54 12 9 94 1 96 101 5
o/p: 101
I/P: Binary Tree
O/P: Print the all pairs which do not follow BST property.
Eg:-
I/p:
7
2 19
8 5 12 17
13 21
46
Looks like formatting is screwed for the binary tree.
http://pastebin.com/raw.php?i=BqrNz9pu
o/p: (8,2) (8,5) (8,7) (13,5) (13,7) (13,12) (19,17) (21,17) (46,17) (46,21)
I told the interview that I would store the inorder traversal of the input binary tree to an array and print out the inversions.
By inversion, I mean if i<j and then if a[i] > a[j]
Given an array of meetings, find out the minimum number of conference rooms required.
class Meeting
{
long startTime;
long endTime;
};
Got 20 minutes to think through and write the code. Too short in my opinion, but well, it seemed like the interviewer didn't understand C++ either :-).
Why we need to override hashcode () and equals method
You are given a n-ary tree. print all the nodes bottom up except for the right most node at each level.
1
2 3 4
a b c d eprint all except 4 (right most at level 1) and e (right most at level 2)
You are given an unsorted integer array consisting of 1's and 0's. You need to rearrange the array with alternating groups of 0's and 1's. The group length is determined by the function f(x)
f(0) = 1
f(1) = 2
f(n) = [square of f(n-1) - square of f(n-2)]
if you run out of either 1's or 0's, then fill the array with whatever is left.
input: 0,0,1,0,1,1,1,0,0,1,0,0,1,1,0,0
output: 0, 1,1, 0,0,0, 1,1,1,1,1, 0,0,0,0,0
f(1) = 1
f(2) = 2
f(3) = sqr(f(2)) - sqr(f(1)) = 3
f(4) = sqr(f(3)) - sqr(f(2)) = 5
f(5) = sqr(f(4)) - sqr(f(3)) = 16
here we don't have enough 0's left to fill the last group. So, we add the five 0's that were left.
Player turns are stored in an array like so [1,2,1,2,1,2,1,2]. Make it so that player 1 finishes first and then player 2. i.e [1,1,1,1,2,2,2,2]
An array contains the following elements [9,6,-3,1,7] and a value is equal to 4. Find a pair of numbers in the array that equal the sum.
Given a circle with N defined points and a point M outside the circle, find the point that is closest to M among the set of N. O(LogN)
Given a preorder traversal, create a binary search tree in optimized time
You are given a file which contains the following information about users visiting the eBay website:
<user id> <type of page visited> <time stamp>
<user id> is a unique key assigned to every user
<type of page> is one of these "home", "search results", "check out", "payment".
The file contains this information sorted according to the time stamp.
A sequence is defined as a continuous set of three types of pages visited by a user.
Example: if a user visits the following pages. "home" -> "search" -> "search" -> "check out"
{home, search, search} is one sequence for the user, {search, search, checkout} is another sequence for the user.
Design and code to determine which sequence occurs the maximum number of times (for all users).
Prints all unique subsets of the string.
Given a string write a function which prints all the subsets of the string. Now make the function to return only unique solutions.
How to design an elevator system. Main thing to worry about is how would you notify the elevator that it needs to move up or down. and also if you are going to have a centralized class to control this behavior and how could you distribute the control.
Write an application in Java to simulate file system. For e.g. implement commands: ls -l (list contents of director sorted by name), cd .. (to go to parent directory), etc. It was a 2 hour remote programming test.
Given a binary tree, how would you copy it from one machine to the other, assume you have a flash drive. I believe we should write the binary tree to file and have the other machine de-serialize it. But how should we do it?
array where indexes correspond to the tree node number of a parent node, and values correspond to current tree node number., root having number -1 Write code to recreate a tree. (I was confusing about what the array index and value really represent)
How to find the smallest number with just 0 and 7 which is divided by a given number?
Given a string, write code to find all the rotations of the string. e.g.
if TOP is original string, then its rotations are: OPT, PTO & TOP itself.
Follow up question: Given two input strings, for e.g. Str1="TOP", Str2="OPT", write a code to find if one is the rotation of the other. If it is a rotation, return true, else return false.
Condition: Do not use hash tables.
Given a N*M grid I want to find biggest submatrix not necessarily a square one that has all the value in it same.
Like
If N=4 and M=5 and matrix is
1 2 3 4 5
1 2 2 2 3
4 2 2 2 6
3 4 5 6 7
Then here answer will be matrix will be
2 2 2
2 2 2
So I need to find upper leftmost coordinate of this submatrix that is [2,2] and bottommost right coordinate that is [3,4].
I was to write a code for it in c++ in my interview
largest number that an int variable can fit given a memory of certain size
Implement a class to create timer object in OOP
What's the tracking algorithm of nearest location to some friends that are located in a grid region?
I have recently attended Amazon Interview and got rejected after design round, its happened three times with Amazon in 2 year, i always getting rejected because of design round. please help me to know how should i answer an design question. questions like 1) design elevator control system 2) design whisper-sync feature (used in Amazon instant video platform) they ask me to design End to end HLD LLD i did not get what exactly differ in both, i explain as a algorithm wise, but could not properly by HLD and LLD.
i mean i searched alot, but could not found a way to answer such question.
Any help will be good for me.
Thanks,
How would you split a search query across multiple machines?
What are Unit and Integrationtesting.
WAP fibonoccaci series using recursion and after completion asked to to write using iteration.
write testcases for the above
how do you test elevator
Difference between blackbox and whitebox
Fill in the following methods:
public interface PointsOnAPlane {
/**
* Stores a given point in an internal data structure
*/
void addPoint(Point point);
/**
* For given 'center' point returns a subset of 'm' stored points that are
* closer to the center than others.
*
* E.g. Stored: (0, 1) (0, 2) (0, 3) (0, 4) (0, 5)
*
* findNearest(new Point(0, 0), 3) -> (0, 1), (0, 2), (0, 3)
*/
Collection<Point> findNearest(Point center, int m);
}Question 2 / 2 (Weighted Stone Arrangement)
You are given an infinite number of stones.
The 1st stone has the weight 1
The 2nd stone has the weight 3
The tth stone has the weight W(t) = 2 * W(t-1) + W(t-2)
Thus, the weights of the first 10 stones are
1, 3, 7, 17, 41, 99, 239, 577, 1393, 3363
Note that you only have one stone of each weight.
You have a weighing machine which is the age old 2-pan balance. You wish to use this machine to measure the weight of an item whose weight is T. The item will always be kept on the right pan. A stone may be kept on either one of the pans. Also, it is not required to use all the stones.
The stones have a weird magnetic property, due to which, the kth stone cannot be in the same pan as the (k-1)th stone. This means that the stone with weight 239 cannot be in the same pan as the stone with weight 99, or in the same pan as the stone with weight 577; and so on.
For example,
T = 11 can be measured as
LEFT PAN: 1, 17
RIGHT PAN: 7
Note that the other alternative
LEFT PAN: 1, 3, 7
RIGHT PAN:
is Illegal since 3 cannot be in the same pan as 1 (or 7 cannot be in the same pan as 3).
T = 21 can be measured as
LEFT PAN: 41
RIGHT PAN: 3, 17
It can be proven that to measure any weight T, there exists a unique arrangement of stones that satisfy the given constraints and measure weight T. Thus, T = 11 or T = 21 can only be measured by the respective arrangements above.
You are given T in the input. Output the arrangement of stones that measures T.
Input Specification
The input contains a single positive integer T.
Output Specification
Output the weights of the stones used on the left pan in increasing order, one number per line. Then output a blank line. Followed by the weights of the stones used on the right pan in increasing order. Note that it is assumed that the item will be kept on the right pan.
If there is no stone kept on the right pan, simply output the weights of the stones used on the left pan in increasing order as above, followed by a blank line.
Constraints
1 ≤ T ≤ 1015
Sample Input 1
11
Sample Output 1
1
17
7
Sample Input 2
21
Sample Output 2
41
3
17
Sample Input 3
1000
Sample Output 3
3
41
239
1393
99
577
Directi Off Campus Interview Process 2013-14
.......................................................................
This is year 4096 and humans have found a medicine for immortality in the year 2048. Tukro a famous online social networking site founded in the year 3072 was celebrating its 1024th anniversary. To celebrate the occasion its CEO, Shark, and his team had launched a unique personalised video of length 17min 4sec for each user. The video consisted of a collage of all popular posts made by the user on Tukro.
Raka shared this video with all his friends without reviewing it. Immediately after he finished watching the 1024 second length clip he realised that he made a huge mistake. The video was made of all posts made by Raka, irrespective of the privacy settings of the individual post.
A post is compromised if a friend who was not supposed to see the original post, has seen it now. Raka wants to know how many of his posts have been compromised. Tukro provides the list of users who have watched the video till now. Help Raka find how many posts were compromised.
Raka has N friends, identified by a unique integer between 0 and N-1.
Raka has L lists of friends, identified by a unique integer between 0 and L-1.
Each list can be of length at the most N.
One friend cannot be added more than once to the same list.
A list must have at least one friend.
A friend may be added to multiple lists.
Visibility of a post in Tukro works through two filters
Include Filter: An array of lists, from the L lists above. Friends can view a post if they belong to any friend list, specified in the Include Filter.
Exclude Filter: An array of lists, from the L lists above. Friends can view a post if their name does not belong to any friend list, specified in the Exclude Filter.
Some caveats of the above are
If no Filter is active, the post is visible to all friends
If only Include Filter is active, a friend can see the post only if he is present in at least one of the lists of Include Filter.
If only Exclude Filter is active, a friend can see the post only if he is not present in any of the lists of exclude filter.
If both Include and Exclude Filters are active, a friend can see the post if and only if
he is present in at least one of the lists of include filter and
he is not present in any of the lists of exclude filter
if he is present in both an include filter list, and exclude filter list, he should not be able to see the post
Input Specification
First line contains a single integer N, the number of friends.
Second line contains a list of integers separated by a single space. The first integer V, represents the number of friends who viewed the video. There are V other integers in the line representing the ID's of friends who viewed the video.
Third line contains a single integer L representing the number of lists.
L lines follow. Each line representing a list. The first integer of the line A, denotes the size of the list; followed by A integers, each denoting the friends in the list.
Next line contains a single integer P denoting the number of posts in the video. 2 * P lines follow. Each pair denoting the Include Filter and Exclude Filters of one post respectively.
First two lines denote the Include and Exclude Filters for first post
Next two lines denote the Include and Exclude Filters of second post
and so on..
An include filter is represented by a list of space separated integers. The first integer B represents the number of lists in the filter. B may be 0, to denote that the include filter is not active. If B is more than 0, the include filter is active and the next B integers in the line denote the ID's of lists present in the include filter.
Exclude filters are also represented in the same format.
Output Specification
Print a single integer specifying the number of posts that are compromised according to the definition above.
Constraints
1 ≤ N ≤ 10000
1 ≤ V ≤ N
1 ≤ L ≤ 6
1 ≤ P ≤ 100000
Note that the constraints on N and P are large.
Your solution will exceed time limits if its complexity is O(N*P).
Even O(V*P) solutions may exceed time limit!
Note the small constraint on L.
Sample Input 1
10
8 1 2 5 6 0 9 8 7
4
2 4 3
2 7 6
3 0 1 5
3 2 8 9
4
0
1 0
1 1
0
0
0
3 1 2 3
0
Sample Output 1
1
Explanation
There are 10 friends. Their ID's are from 0 to 9
8 of them viewed the video = {0,1,2,5,6,7,8,9}
There are 4 lists
List-0 has 2 friends {3,4}
List-1 has 1 friend {7,6}
List-2 has 3 friends {0,1,5}
List-3 has 3 friends {2,8,9}
There are 4 posts
Post-0 doesn't have any include filter but has List-0 - {3,4} - in exclude filter
3, or 4, have not seen the video
Hence Post-0 is not compromised
Post-1 has an include filter of List-1 - {7,6} - and no exclude filter.
But other friends have seen the video
Hence Post-1 is compromised
Post-2 doesn't have any filters. Such a post was intended to be seen by anyone.
Hence Post-2 is not compromised.
Post-3 has a include filter of List-1, List-2 and List-3.
Their union is {0,1,2,5,6,7,8,9}
These are the exact friends who saw the video
Hence Post-3 is not compromised
Hence only 1 post is compromised.
Sample Input 2
5
2 2 3
5
1 0
1 1
1 2
1 3
1 4
4
3 2 3 4
1 0
3 1 2 3
0
3 0 1 3
0
3 2 3 4
1 0
Sample Output 2
1
Consider 0 as water and 1 as land. Write code in C to find out whether there is pool in the following matrices.
11111
10001
10001
11111
above matrix is pool
11111
11001
11001
10111
11111
above matrix is NOT pool
11111
11001
11001
10001
11111
above matrix is pool
11111
11101
11001
10001
11111
above matrix is pool
Implement the queue using stack
Implement the stack using queue
def inc:
while True:
v = v + 1 //---A
set(s) // ---B
def disp:
while True:
wait(s) //---C
print v //----D
print all possible value, which is shared value. At the begin , v = 0
s is binary semophore. initial value is 0
Given a list of strings. Produce a list of the longest common suffixes. If it asks for longest common substring, then building a suffix tree should be the way to go. But how should we implement this if it is for longest common suffixes?
Given a source string say "xxyyxxx" and a destination string say "xxxxyyx" and the number of steps, determine whether the source can be changed to the destination in the given steps..
One step is where you can change x to y or y to x or rotate the whole string by 1 element either left of right..
Example:
xxxyyxx and yxxxxxy and steps 5
Answer would be yes, as we can reach the number by rotating 3 steps and swapping a character twice..
Given a string S1, convert it to another string S2 (Anagram) by swapping only adjacent elements. Print all the intermediate strings formed.
eg: s1: abcde
s2: bcdae
output: bacde,bcade, bcdae.
like wise.
Given N Vertices and M Edges. Each Edge connects two vertices.
There is at most one way to move between each pair of vertices.
Each vertex is either locked or unlocked .There is a perfect path between two different vertices if both vertices are unlocked, and are connected with each other by some way.
The question is What is the number of pairs of vertices, which have a perfect path between them and also What is the number of the vertices, which have at least one perfect path passing through that vertex.
NOTE : There is at most one way to move between each pair of vertices, that is, the given graph is a forest
EXAMPLE : Say we have 6 Vertices and 5 Edges.
A=[1,1,1,1,1,0] It shows that A[i]=1 if ith vertex is unlocked otherwise 0.
Let the connected pair of vertices are : (1,2),(1,6),(1,5),(2,4),(4,3)
Here ,Answer for first question is 10 and second one is 5.
So,interviewer asked me to device an efficient algorithm for it and also code it in c++
Given a matrix, you need to create another matrix such that the value (i,j) is either -1, 0 or 1.
1 - if multiplication of all values in ith row and jth column is greater than 0.
-1 - if multiplication of all values in ith row and jth column is less than 0.
0 - if multiplication of all the values in ith row and jth column is 0.
e.g.
1 2 3 1
1 0 -1 2
-1 1 1 1
o/p
-1 0 -1 1
0 0 0 0
1 0 1 -1
Given a list of countries with their population, write a method to pick any country such that the probability of it being chosen is proportional to its population
This was asked to one of my friends in her telephonic interview with ADP.
Imagine you have a 5x5 matrix containing integers... If any of the elements in this original matrix is 0, then your resultant matrix should have the corresponding row and column filled with 0s. For e.g. if 1st element of 1st row, 2nd element of 2nd row......up to 5th element of 5th row are all 0s, then your resultant 5x5 matrix should be all 0s. Your code should be flexible and work for any size of matrix (not just with 5x5).
A number of intersecting bridges is given.Remove minimum number of bridge to make remaining bridges non-intersecting.
Given linked list as a-x-b-y-c-z
output it as a-b-c-z-y-x
that is reverse alternate element and append to end of list
Given a kernal code in "0"th machine. How soon you can replicate the kernal across N machines. Now if the machines has upload and download bandwidth constraints, how can you impove the copy time.
If you have data coming in rapid succession what is the best way of dealing with redundant data?
In a book with N pages, pages are numbered from 1 to N. Find out how many times
each digit occurs in that book.
You are expected to complete the function getDigitslnBook, which takes an integer as input and
prints how many times each digits occur, one in a line.
The Nth line in the output denotes how many times the integer N-1 occurs in page numbers.
Constrains:
N will be between 1 and 1,000,000,000, inclusive.
The output will fit in an integer.
Sample lnputOO:
7
Sample Outputo : 0
1
0
0
Explanation :
The page numbers are 1,2, 3,4, 5, 6 and 7.
Sample lnput01: 11
Sample Output01:
1
4
Explanation:
Digit 1occurs 4 times, at 1,10 and 11.Rest of the digits occurs only once.
How would you use Dijkstra's algorithm to solve travel salesman problem, which is to find a shortest path from a starting node back to the starting node and visits all other node exactly once.
I was asked a question in an interview.
On an office floor , there are e entities - Walls , Cubicles , Coffee Rooms.
In what data structure we should store this design that when a new member joins the company , the cubicle number which is empty and next closest to any coffee room should be assigned to it.
Basically , data structure DS.pop() should return that cubicle number in the most efficient way.
A Person can walk through cubicles to reach a coffee room but not through walls.
How does trie handle scalability as opposed to hashtable? Assuming it is used for a dictionary. Sclability here should cover large size of input, running out of memory, or even running out of memory on multiple machines if distributed system is used.
given 2 arrays wrds[] , chars[] as an input to a function such that
wrds[] = [ "abc" , "baa" , "caan" , "an" , "banc" ]
chars[] = [ "a" , "a" , "n" , "c" , "b"]
Function should return the longest word from words[] which can be constructed from the chars in chars[] array.
for above example - "caan" , "banc" should be returned
Note: Once a character in chars[] array is used, it cant be used again.
eg: words[] = [ "aat" ]
characters[] = [ "a" , "t" ]
then word "aat" can't be constructed, since we've only 1 "a" in chars[].
Given the following 3 by 3 grid where the (first row, first column) is represented by (0,0):
0,1 1,2 3,3
1,1 3,3 3,2
3,0 1,3 null
we need to find if we can get to each cell in the table by following the cell locations at the current cell we are at. We can only start at cell (0,0) and follow the cell locations from that cell, to the cell it indicates and keep on doing the same for every cell.
Given a Text String T: abbbacctlkjlkcccaaabbb and pattern string P: ab[.]*c[.]*b, Find all occurances of P in T
Given a Text String T: aaabbbzzccc
and pattern string P: ab , Find all occurances of P in T
Write a Program for Dictionary which has functionality of lookup and insert . This program should be able to add words on the fly
I wrote simple code using HashTable
follow up
1) Now we are getting too many words what happens
me: Hashtable will dynamically resize resulting into performance hit . Also they might get hashed to same location as well as we might run out of main memory
2) Okay you are out of main memory , How will you scale this program
me: I will create buckets of HashTable lets say 26 buckets for one for each alphabet and would put them on different machines
3) Lets say you are out of memory on those machines too
me: Okay I need to put them on secondary storage . Here we can have fileSystem or Database . I chose database . I will create simple DB schema of BucketNumber and word .
I will use buckets on main memory as cache , if we are not able to find a word in the bucket then query databse with bucket number and words then remove the least number times looked up word (every time we lookup a word we increament the count i.e value in key,value pair on hashtable) from that bucket and add this word .
I mentioned that bottleneck in this case will be every time a word is not present we need to query DB which usually has high latency which will result into performance hit
4) Lets say we are okay with latency but what if we are getting inserting words between that are only between only in two buckets ex. words starting from a and b only.
Now that I think about it, is it better to do this in a trie? What do you guys think?
Given an input string and a dictionary of words, find out if the input string can be segmented into a space-separated sequence of dictionary words. You need to output the minimum number of words. For example, input: "aaaisaname"
dict: ("a", "aaa", "is", "name")
output: "aaa is a name"
Wrong output: "a a a is a name"
You have two sorted list. Write code for returning the first k elements. K may be a large number like 10 million.
You have a lists with integers. Find all the pairs of numbers that sum less than or equal to to a particular number k. The list contains minimum 5 Million number.
(I provided a n^2logn solution but they may be looking forward to having a better answer).
Find a triplet that sum to a given value in an array of integers. I know it can be done in O(n^2) with either using a hashmap(space O(n)) or pre-sorting(space O(1)) the array. Is there any way to do this better than O(n^2)?
Implement a sudoku solution verifier function. The rules for sudoku is this:
You have a 9 by 9 board. This board is divided into nine rows, nine columns, and nine 3x3 blocks. In a solved puzzle, every row, every column, and every 0 block has to contain each of the digits from 1 to 9. This is an example of a solved puzzle:
248|395|716
571|628|349
936|741|582
---+---+---
682|539|174
359|174|628
714|862|953
---+---+---
863|417|295
195|286|437
427|953|861Given a set of numbers, find those numbers that occur odd number of times. I used the hash table approach where I insert the count (no. of times occurred as of now) of the current number whose hash I am making. Time complexity: O(n). Space complexity: O(n).
Find the smallest number m(>0) whose product of digits equal to a given number n.
ex:- n = 24 and m = 38
n = 12 and m = 26
Design a program that would select which elevator in a building would be the most efficient, based on where the elevator is located and headed and where the user is located and headed.
Print all the elements in an array that have occurred an odd number of times. I know we can XOR all numbers, but that only solves the problem where there is only one odd number in the array. But I was asked to find all of them. Another method I can think of is to keep one hashset, then walk through the array, if the number is in the map, remove it. If the number is not present, add it. But this requires O(n) space. Is there any way to do this with O(n) time and O(1) space?
You are trying to cook an egg for exactly 15 minutes, but instead of a timer, you are given two
ropes which burn for exactly 1 hour each. The ropes, however, are of uneven densities – eg,
half the rope length-wise might take only 2 minutes to burn?
public interface Intervals {
/**
* Adds an interval [from, to] into internal structure.
*/
void addInterval(int from, int to);
/**
* Returns a total length covered by intervals.
* If several intervals intersect, intersection should be counted only once.
* Example:
*
* addInterval(3, 6)
* addInterval(8, 9)
* addInterval(1, 5)
*
* getTotalCoveredLength() -> 6
* i.e. [1,5] and [3,6] intersect and give a total covered interval [1,6]
* [1,6] and [8,9] don't intersect so total covered length is a sum for both intervals, that is 6.
*
* _________
* ___
* ____________
*
* 0 1 2 3 4 5 6 7 8 9 10
*
*/
int getTotalCoveredLength();
}A(1) = ()
A(2) = (())
A(3) = (()) ()
A(4) = (())() (())
A(5) = (())()(()) (())()
A(N) = A(N-1) + A(N-2)
I/P: N, i
O/P: A(N).charAt(i);
Interviewer was not looking at iterative or recursive solution. He was looking at a closed form solution.
Given an array of numbers find the maximum count of duplets and triplets such that there sum is a multiple of three. Number that has appeared once can’t be included anywhere else.
Given an array of n distinct integers sorted in ascending order. Find an index i s.t ar[i] = i. Return -1 if no such index exists. Note that integers in array can be negative.
Write a program for finding a minimum element in rotated sorted array(either ascending or descending ) and array contains duplicates.
Write a program find minimum element in the rotated sorted array( ascending or descending ) and array having duplicates elements.
Suppose you are a project manager and you're certain your project is going to be late. What actions should you take?
What are the most important things to a software development project?
What is integration testing?
What types of security testing do you know? do you know SQL injections?
Give us an example of meeting a deadline that you are particularly proud of
What is your greatest failiure?
Do you know any C#?
Are you familiar with .NET?
What is polymorphism? what does it do?
What are design patterns?
There are N objects kept in a row. The ith object is at position x_i. You want to partition them into K groups. You want to move all objects belonging to the same group to the same position. Objects in two different groups may be placed at the same position. What is the minimum total amount by which you need to move the objects to accomplish this?
Input:
The first line contains the number of test cases T. T test cases follow. The first line contains N and K. The next line contains N space seperated integers, denoting the original positions x_i of the objects.
Output:
Output T lines, containing the total minimum amount by which the objects should be moved.
Constraints:
1 <= T <= 1000
1 <= K <= N <= 200
0 <= x_i <= 1000
Sample Input:
3
3 3
1 1 3
3 2
1 2 4
4 2
1 2 5 7
Sample Output:
0
1
3
Explanation:
For the first case, there is no need to move any object.
For the second case, group objects 1 and 2 together by moving the first object to position 2.
For the third case, group objects 1 and 2 together by moving the first object to position 2 and group objects 3 and 4 together by moving object 3 to position 7. Thus the answer is 1 + 2 = 3.
if EVER + SINCE = DARWIN , then what is D+A+R+W+I+N?sort the array so that the odd number in front of the even number and their relative order doesn't change in Time O(n) and Space O(1). I believe quickselect can do this, but it will change the relative order of the input.
/**
* Return the smallest character that is strictly larger than the search character,
* If no such character exists, return the smallest character in the array
* @param sortedStr : sorted list of letters, sorted in ascending order.
* @param c : character for which we are searching.
* Given the following inputs we expect the corresponding output:
* ['c', 'f', 'j', 'p', 'v'], 'a' => 'c'
* ['c', 'f', 'j', 'p', 'v'], 'c' => 'f'
* ['c', 'f', 'j', 'p', 'v'], 'k' => 'p'
* ['c', 'f', 'j', 'p', 'v'], 'z' => 'c' // The wrap around case
* ['c', 'f', 'k'], 'f' => 'k'
* ['c', 'f', 'k'], 'c' => 'f'
* ['c', 'f', 'k'], 'd' => 'f'
*/
Explain some of the text encoding types and advantages/disadvantages of each.
If your browser crashes, how would you debug it only using the command line?
There are 3 ants at 3 corners of an equilateral triangle they randomly start moving towards another corner what is the probability that they do not collide? Follow up: Suppose if all ants go in same direction(say ant 1 travels from point A to B, ant 2 from B to C and ant 3 from C to A. Either all ant travels in clockwise or anti clockwise) when will they collide
design an iterator over a LinkedList of LinkedList's
How will you sort 1 billion integers stored in an array?
Having two distinct very large ordered array of values, find the mean value(not median) of the two arrays.
You have a 100 coins laying flat on a table, each with a head side and a tail side. 10 of them are heads up, 90 are tails up. You can't feel, see or in any other way find out which side is up. Split the coins into two piles such that there are the same number of heads in each pile.
Model an elevator.
Implement an iterator for a binary search tree that will iterate the nodes by value in ascending order
Create a class that supports the following methods:
void setup(List<String> words) : This adds a bunch of words into this structure that can be matched later. Words optionally could contain "." wildchar character(s) that matches any char.
boolean isMatch(String word) : Given a word that optionally might contain "." wildcard character(s), does it match any word in the words provided in setup.
For example:
Setup -> { "hello", "mi." }
isMatch("hello") -> true
isMatch(".ell.") -> true
isMatch("hel.a") -> false
isMatch("hel.") -> false
isMatch("mix") -> true
What happens during and after a query is being typed (autocomplete) in a search box whether the user is trying to go to a website or asking a question etc, and how do servers complete the request and what is the best (parallel) structure for the request to go through. DFS and how servers are located for proximity
To find loop in a circular linked list, we generally move two pointers , one with speed of one move at a time and other at two at moves at a time. Why do we use ratio 2:1. What can be the best ratio of speed to find a loop in linked list
Given N,find all a and b combination which satisfies a^3 + b^3 = N
Write code to return a random line from a file of unknown size and variable length rows
How to remove duplicate lines in a large text file? I think it's easy to find duplicate lines, but how do we efficiently remove them from the file?
Given a stream of characters, find the first non-repeating character in the stream. You can go through this stream only once
Search in a rotated array for a given integer, it can be rotated clockwise or anticlockwise. Handle both
Design the system for Amazon website where if you purchase an item X , it shows "Customers who bought X also bought A,B,C items".
Assume: if a customer buys A,B,C items in his history then they are all related and each one should appear in others
Design Coffee Shop? Follow up: Extend this to handle multiple coffee shops (Ex like starbucks and across countries)
How is printf implemented?
Given an input string.
* It has numbers from M to N in increasing order. But no prior information about the values of M and N.
* There is one missing number.
Output the missing number.
Eg.
I/p: 960961962964
O/p: 963
I/p: 12345789
o/p: 6
How would you design a chess game in OOP?
Given inputs from Google Search, you have K chunks. Each chunk is individually alphabetically ordered (apple, banana, cat) ... (*apple, *banan, *cat). You want to merge all chunks into a single list. How would you do it?
How do you implement stack in stl? What is the complexity?
I have 5 arrays with integer elements. I want to find the common elements in all 5 arrays. What is the logic?c
What is smart pointer? How do you implement? What happens with the following: p2 = p1;
What happens P3(p1) (copy const)?
given 2 Dimensional array
I/P -- String[][] input = { { "abc", "def", "gh" },
{ "f", "g" },
{ "qrt","xyz","pqr" } };
Program shd return a 2-D Array with
O/P -- { { "abcfqrt", "abcfxyz", "abcfpqr" ,abcgqrt and so on ..
Count the number of positive integers less than N that does not contains digit 4.
If you had a savings account with $1, at a 100% interest rate, at what year would you have 15 billion dollars? I know it's Log base 2 of 15 billion. But how did it get to log base 2? What's the formula here?
The setup is that we are given a series of text files which contain information regarding a code repository's commits. Each file represents a single commit and they are formatted as follows:
"
Commit #: XXX
Author: XXX
Reviewer(s): XXX, XXX, ...
File: XXX
File: XXX
...
Date: XX:XX:XX XX/XX/XXXX
"
The commit number is unique and is generated in synchronous order. There is exactly 1 unique author. There are a variable number of reviewers, delimited by commas; if there are no reviewers, that line is absent from the file. There are a variable number of edited files in the commit, each receiving its own line. The time/date is when the commit was submitted.
First design a graphical model for all of the commit data. Then describe how this model is updated when a new commit is generated. Finally, write the code segment called when a new commit is generated which edits a system that has implemented your model of the data - its input is a file name and whatever necessary data structures that are maintained by your system.
How to design a file system in OOP. I believe we can use composite pattern to model in which we create an abstract class say Entry, and have directories and files extend from it. In Directories, it has a List<Entry>. How should we write the remove method so that it will recursively remove all of its sub-directories and sub-files then do parent.remove(this)? Also, how should we take read/write permission into account?
There is an array of Boxes and you need to pick one at random. Each Box has a integer weight and a boolean function specifying whether it is eligible to be picked.
struct Box {
bool canBePicked();
int getWeight();
}
If the Box is eligible to be picked, the weight determines the probability it will be picked. For example, let's say there are three Boxes A, B, and C. A and C are eligible to be picked. If A has weight 2 and C has weight 1, A should be picked with probability 2/3 and C should be picked with probability 1/3.
Design an algorithm for picking a Box from the array.
Find minimum distance between two words (order preserved) in a big string.
For e.g 1. "hello how are you" - distance between "hello" and "you" is 3.
e.g 2. "hello how are hello you" - distance is 1
e.g 3. "you are hello" - distance is -1. Order of "hello" and "you" should be preserved.
e.g 4. "hello how are hello" - distance is -1 since "you" didnt occur even once.
Given a timer time() with nanosecond accuracy and given the interface
interface RealTimeCounter:
void increment()
int getCountInLastSecond()
int getCountInLastMinute()
int getCountInLastHour()
int getCountInLastDay()implement the interface. The getCountInLastX functions should return the number of times increment was called in the last X.
(My note: an ideal solution will have space usage which does *not* grow unbounded with the number of calls to increment(). It seems to me that a solution involving a round-robin database could be good, but it sacrifices accuracy.)
How you can find whether a link list contains a cycle or not?
Show whether two integer ranges are overlapping or not. If so, return the overlap range
given a double linked list and an array of nodes in that dll,output number of clusters. example: dll: n1 n2 n3 n4 n5; array: n1 n4 n5; output 2( (n1) (n4 n5))
given string of chars,find way to compress consecutive char with no ambiguity. example:daaad
to d4*ad; 5eeeecd to 5*14*ecd
Lucky numbers are those numbers which contain only "4" and/or "5". For example 4, 5, 44, 54,55,444 are lucky numbers while 457, 987 ,154 are not.
Lucky number sequence is one in which all lucky numbers exist in increasing order for example 4,5,44,45,54,55,444,445,454,455...
Now we concatenate all the lucky numbers (in ascending order) to make a lucky string "4544455455444445454455..."
Given n, your task is to find the nth digit of the lucky string. If the digit is 4 then you have to print "Hacker" else you have to print "Earth".
Input:
first line contain number of test cases T , next T line contain a single interger n.
Output:
For each test case print "Hacker"(without quotes) if nth digit of lucky string is "4" else print "Earth"(without quotes) if nth digit of lucky string is "5".
Constraints:
1<=t<=10^5
1<=n<=10^15
Problem Statement
There are three types of tickets and stations available in CodeCountry A, B and C. Tickets of type A can only be bought at stations of type A and end at a station of type B. Tickets of type B can only be bought at stations of type B and end at a station of type C. Similarly, tickets of type C can only be bought at stations of type C and end at a station of type A. Also, you can only travel from station i to station j if j > i, i.e. you can only move forward and if the ticket type bought at station i ends at station j.
The cost of a ticket is j x j if you travel a distance of j. For example if you start at Station 3 and end at station 5 the cost is 2 x 2=4.
Now, you want to travel from Station 1 to Station N using trains in CodeCountry. You are given the type of each station. Output the minimum cost of the journey.
Note that station N will also have a type and you must reach it using a ticket of compatible type. Output -1 if it is not possible to reach from station 1 to station N
Input Format
The first line contains the number of test cases T. This is followed by T lines one for each test case.
Each test case consists of a string representing the types of each station. The i-th character of the string represents the i-th station's type.
Output Format
Output the minimum cost of the journey, one line per test case.
Constraints
The number of test cases is atmost 50.
There will be atleast 2 stations and atmost 15 stations.
The first station (station 1) is always of type A.
Write a routine that does secret santa in O(N) time. I don't really understand what it means by 'does secret santa' actually.
How would you design a social network and find or keep track of someone's oldest friend in a social network? Oldest friend means the friend that you have added for the longest time period. My solution to the first question is to represent friendship in a graph , storing a list of friends in each User object, and use breadth-first-search to find connection. Not sure about the second question though. My idea is either keep a reference to the oldest friend as a member field, or have a double linked list of users sorted by the start date of friendship.
i have an array{{1,2,3},{4,5,6},{7,8,9}}.I want output=1,2,4,3,5,7,6,8,9
We have a list of N nodes with each node pointing to one of the N nodes.
It could even be pointing to itself. We call a node ‘good’,
if it satisfies one of the following properties:
* It is the tail node (marked as node 1)
* It is pointing to the tail node (node 1)
* It is pointing to a good node
You can change the pointers of some nodes in order to make them all ‘good’.
You are given the description of the nodes.
You have to find out what is minimum number of nodes that you have to change in order
to make all the nodes good.
Input:
The first line of input contains an integer number N which is the number of nodes.
The next N lines contains N numbers,
all between 1 and N.
The first number, is the number of the node pointed to by Node 1;
the second number is the number of the node pointed to by Node 2;
the third number is the number of the node pointed to by Node 3 and so on.
N is no larger than 1000.
Output:
Print a single integer which is the answer to the problem
Sample Input 1:
5
1
2
3
4
5
Sample output 1:
4
Explanation:
We have to change pointers for four nodes (node #2 to node #5) to point to node #1.
Thus 4 changes are required
Sample input 2:
5
5
5
5
5
5
Sample output 2:
1
Explanation:
We have to just change node #5 to point to node #1 (tail node) which will make node #5 good.
Since all the other nodes point to a good node (node #5), every node becomes a good node.
Generate MAX_INT (Max signed int value) using bitwise operators. Should work in 32 and 64 bit processors
By mistake I wrote the following program and it compiles and runs without any error in gcc compiler. enter code here
#include<stdio.h>
#include<stdlib.h>
int main()
{
int i,**data;
data=(int **)malloc(sizeof(int)*1000000);
for(i=0;i<1000000;i++)
data[i]=(int *)malloc(sizeof(int)*1000000);
printf("done\n");
return 0;
}
But I don't understand how is it allocating an array of 1000000*1000000 bytes,almost equivalent to 1TB??
Given 2D matrix of chars, you can find substring by moving in any [of 8]direction inside the range.
Get the list of sorted palindromes without duplicate which are available inside all possible substring in the Matrix.
Find the digits count in the number from Range 0-n
For Example: Input range 0-10
count[0]=2
.
.
.
count[9] =1
I have declared one double pointer character array as given below:
char **errorcode;
so how to initialize this array with NULL.
and pass to other function?????
There are 2 arraylists each consisting of 1 million records.
Give me the same objects present in both the lists.
The objects in the list can be any thing of our choice.
Imagine you're designing a Web Service for a phone application that returns a list of suggested Words that may complete a given string the user types.
For example, if the user writes "ap", a list of suggested words may contain ["apple", "application", "aptitude", ...].
Assume English only words and no misspelling.
I gave a solution with tries and interviewer asked for an alternative solution (I was thinking something along the lines of hashing but time ran out and I couldn't put together anything concrete). I mentioned a couple ways I could optimize my idea, but felt short on that area. For example, ways to return smaller lists, ranking, caching, etc.
Determine if a tree is a valid BST with no duplicated values. (This means that if the binary tree has a duplicated number it should return "invalid" even if it's an actual BST)
I gave an O(n) solution and interviewer seemed happy with it.
You have a plain with lots of rectangles on it, find out how many of them intersect
Sort a list of numbers in which each number is at a distance k from its actual position
Store a set of sudden-death tournament results in a compact format (eg. a bit array) and a set of predicted match results (also in a bit array). Score the predictions, giving one point per correctly guessed match, without unpacking the bit array into a more convenient format (ie. you have to traverse the tree in-place).
Implement a simple regex parser which, given a string and a pattern, returns a boolean indicating whether the input matches the pattern. By simple, we mean that the regex can only contain special character: * (star), . (dot), + (plus). The star means what you'd expect, that there will be zero or more of previous character in that place in the pattern. The dot means any character for that position. The plus means one or more of previous character in that place in the pattern.
1. find all the combinations of a string in lowercase and uppercase. For example, string "ab" -> "ab", "Ab", "aB", "AB". So, you will have 2^n (n = number of chars in the string) output strings. The goal is for you to test each of these string and see if it match a hidden string.
int[] first = {3}; // size 1
int[] second = new int[3]; // size 3
second[0] = 2;
second[1] = 4; //2,4
Second array has enough space to hold all elements of first and second array, where both the arrays are merged. Now write code to have first array into second.
The following Cracking the coding interview code doesn't work.
public static int[] merge2(int[] first, int[] second){
int lastA = first.length-1; //0
int lastB = second.length-1; //2
int indexMerge = (lastA + lastB);
while(lastA >= 0 && lastB >= 0){
if(first[lastA] > second[lastB]){
second[indexMerge] = first[lastA];
indexMerge--;
lastA--;
}else{
second[indexMerge] = second[lastB];
indexMerge--;
lastB--;
}
}
while(lastA >= 0){
second[indexMerge] = first[lastA];
indexMerge--;
lastA--;
}
return second;
}
remove duplicates of a linkedList
follow up, can you do it without an extra buffer (or temporal storage )
Implement an algorithm to delete a node in the middle of a single linked list, given
Implement an algorithm to find the nth to last element of a singly linked list.
You have 2 list with a single digit only. representing a number. Return a list with the result of adding both list.
Reverse of a LinkedList
follow up
Can you do it recursively?
Steps Problem,
Givin n, find how many different ways you can take steps to reach the top
E.g.
findSteps(4)
1,1,1,1
1,1,2,
2,2
1,3,
4
this would return 5
Struct node{
node *pNext;
node *pRandom;
};
You have a link list of the above node structure. pRandom has connection to any random nodes.
Write a program to clone this list.
note:You should not add any new items to node
Write a program to find the GCD of two numbers
Forgot to add this question along with my previous...
This is a brain teaser type question...
S E N D
+
M O R E
--------------
M O N E Y
--------------
Each of the above characters hold a specific value which is unique (meaning no two characters have same value). Now the question is, to uncover what value each character stands for...
(Hint - 'M' has to be 1 because it's the carry in the result (M O N E Y). Now similarly back track the rest of the characters)
Note: this hint is given by me, for the sake of understanding the question for interested folks, it was not given to me in the interview).
Given a sorted 2D matrix. Find the median.
Given a number N, now find the smallest number K such that product of digits of K is equal to N. If there is no such K then return -1.
Suppose N = 100, then K = 455
N=26, K = -1
Given a number N, now find the number of occurrences of each digit 0..9 from 0 to N
Eg:
i/p: 12
o/p:
2
5
2
1
1
1
1
1
1
1
A typical Change Making problem but a bit twisted. Given a large amount and the denominations given, I need to come up with total number of ways in which the amount can be made using RECURSION. The signature of the function is as follows
int makeChange(int Amount, int[] Denominations)A
Amount-Total Amount
Denominations- The available denominatins.
It returns total number of ways.. make sure this has to be done Using Recursion..
Given an input like:
[2, 4]
[1, 2]
[3, 6]
[1, 3]
[2, 5]
Use it to reconstruct this binary tree:
1
2 3
4 5 6
Note that:
a) The first number in each line is a parent.
b) Second number is a child.
c) The left child always shows up in the input before the right child.
Return root.
You are given an array A with elements 0 to n-1, numbers can be repeated in the array. Create n sets where
S[i]={a[i],a[a[i]],a[a[a[i]]]…}. Set has all elements unique. Find the size of the largest set.
Input:
First line contains n, size of the array. n<1000
Next lines contains n numbers, each element of the array
Output
Prints one number: Size of the largest set.
Sample Test Case:
Input: {3,1,2,0}
Output: 2
Explanation:
Four possible sets are
{3,0},{1},{2}{0,3}
Given an array of integers. Remove minimum number of elements from the array such that the largest and the smallest number does not differ by more than two times.In other words if x is the minimum of the remaining elements in the array and y is the maximum than y<=2x.
Find the minimum number of numbers that has to be removed from the array so that the largest and the smallest number differed in no more than two times.
Input:
First line contains n(2<=n<=10^5), the size of the array
Second line contains n integers, the elements of the array.
Output:
Single integer - the minimum number of elements to be removed from the array.
Sample Test Case:
Input: {4,5,3,8,3,7}
Output: 2
Note: In the above sample you can remove the fourth and the sixth measurement results (values 8 and 7). Then the maximum of the remaining values will be 5, and the minimum one will be 3. Or else, you can remove the third and fifth results (both equal 3). After that the largest remaining result will be 8, and the smallest one will be 4.
You do not need to write full code. Just fill out the given function.
You are given a 2-Dimensional array with M rows and N columns. You are initially positioned at (0,0) which is the top-left cell in the array. You are allowed to move either right or downwards. The array is filled with 1's and 0's. A 1 indicates that you can move through that cell, a 0 indicates that you cannot move through the cell. Given a function numberOfPaths which takes in the above 2-D array, return the number of paths from the top-left cell to the bottom-right cell (i.e. (0,0) to (M-1,N-1)).
you have a array which says the order of alphabets say [abcdef....z]. now use this array to sort, constraint is 'a' can be swapped one time 'b' two times, and for sorting you can use only swap.
you have n different array, all are sorted. form one array of size n whose range is min. meaning in resultant array diff of a[0] to a[n-1] is min.
You are given numbers from 1 through 100 in an array, there is one number missing, find that one
i have 2 class class employee which has empname and Title(manager,team lead) and class person which has name age and gender.. now i need to create a hasmap which has key and value pair as employee and person and if i give employee as key it should give me person values and if i give person as key it should give me employee value
Suppose you are given one number decomposed in binary representation.
Input : 101011
Output : 000000
Needs to write algo and tell the approach in how efficiently we can flip the given input numbers to all zero's
Interviewer not mentioned about time complexity but it should be very efficient.
In Linux, we use virtual address.So each process will think it has 4 GB
memory space even if the real memory is only 2GB. Now suppose we do not have
MMU and programmer use real physical address in their program. We only have
small size of physical memory. How can we design the system?
We run two video game benchmarks on our new designed SOC. The two
benchmarks have the same instruction set. The benchmark with higher power
consumption always work well while the other one always get stuck. What can
be the problems?
In the new mobile phone, we can either choose to use a 1GHz solo core or
500MHz duo core processor. What tradeoffs should we consider?
This is a hardware design problem. I can not figure it out. Suppose we have 2 pipelined hardware multipliers(or something). One is working at 1GHz with 2 operations executed in parallel at the same time. The other one is at 500GHz with 4 operations. Suppose we have transistors of 3 types(low leaky(30%),middle leaky(50%) and high leaky(70%)) and here leaky means leakage power of the transistor. Which multiplier should we use considering the 3 types of transistors.
Given an input like:
[2, 4]
[1, 2]
[3, 6]
[1, 3]
[2, 5]
Use it to reconstruct this binary tree:
1
2 3
4 5 6Edit: The "1" is the root, I dont know why is aligning to the left
Note that:
a) The first number in each line is a parent.
b) Second number is a child.
c) The left child always shows up in the input before the right child.
Return root.
You as a developer are tasked to create an application that builds invoices that are send out to the company’s clients. Invoices are sent to the client’s address and the client should pay the invoice amount by a given date otherwise fees could incur. The client should be able to see detailed information about the items they are being billed for, like item cost, tax, quantity, etc. The client can be billed for products and/or services. Services are not taxable and product tax varies by client zip code.
Using the objected oriented language of your choice; design an object model for this application.
Design a job scheduler.
Design news aggregator like google news, without using pull, push or page crawl. Explain how are you going to scale it.
Write a method to print output of a^b
Suppose there is array contains 100 unsorted elements ...say a[1] to a[100].
find out the minimum and maximum value in the range of a[25] to a[75].
Implement an algorithm to determine if a string has all unique characters. What if you can not use additional data structures?
Design an algorithm and write code to remove the duplicate characters in a string without using any additional buffer. NOTE: One or two additional variables are fine.
Write a method to decide if two strings are anagrams or not.
Write a method to replace all spaces in a string with '%20'.
Given an image represented by an NxN matrix, where each pixel in the image is 4 bytes, write a method to rotate the image by 90 degrees. Can you do this in place
Write an algorithm such that if an element in an MxN matrix is 0, its entire row and column is set to 0
Assume you have a method isSubstring which checks if one word is a substring of another. Given two strings, s1 and s2, write code to check if s2 is a rotation of s1 using only one call to isSubstring (i.e., “waterbottle” is a rotation of “erbottlewat”).
Write a prog in any language you are comfortable, which takes 2 strings as an input and then finds the first occurrence of the first string in the second string. The function should return the index in the second string where the match was found.
Tip : The basic algorithm here is to iterate through the second string and when the char matches the first char in the 1st string., check if subsequent substring is a match, and return if it is.
I wanted to know if someone knows how to solve this algorithm in C#!!!
I do not know this programming language that well and need it converted, you do not have to solve the algorithm but it would help if you can!
// You are free to implement the solution in C, C++ or C#.
// You are given a set of numbers stored in your own implementation of queue
// and another set of numbers stored in your own implementation of stack.
// The goal is to calculate the sum of those two sets of values.
// NOTE: You must implement your own Queue and Stack.
//
// Inputs:
// num1 = 123456
// num2 = 654321
// Output:
// result = 777777
#include <stdio.h>
#include <tchar.h>
//yourQueue implementation
//yourStack implementation
// Please use either String or char*
char *yourAdd (yourQueue *num1, yourStack *num2)
{
char *result = 0;
// Your code.
return result;
}
void main(int argc, _TCHAR* argv[])
{
yourQueue *num1; //should only be able to push 0-9. num1->push(10) is invalid
num1->push(1);
num1->push(2);
num1->push(3);
num1->push(4);
num1->push(5);
num1->push(6);
yourStack *num2; //should only be able to push 0-9. num2->push(10) is invalid
num2->push(1);
num2->push(2);
num2->push(3);
num2->push(4);
num2->push(5);
num2->push(6);
char *result = yourAdd(num1, num2);
printf("result: %s\n", result);
}
Given a kernal code in "0"th machine. How soon you can replicate the kernal across N machines. Now if the machines has upload and download bandwidth constraints, how can you impove the copy time.
Given a binary tree, link every node's sibling pointer to its next sibling on the same level so these sibling pointers consist a single linked list on each level. Requirement: use O(1) space.
Please suggest best algorithm for following scenario:
We have two ArrayList containing Integer values, Both are unordered, have repeating elements and contains thousands of Integer objects.
Example : L1 - 2,4,1,1,6,4,3,1.... and so on
: L2 - 9,2,1,2,1,23,34,.. and so on
Both list contains large amount of data.
We need to get List of non repeating elements from both of them. For example consider L1 and L2 output list should contain 9, 3 23,34 as remaining elements are available in both lists.
how we make a spftwre for pc
In the Amazon Office, Employees are use to sit in cubical offices and all the offices are connected with some other offices, but they are not arranged in any well defined order. Offices are connected means they are sharing their walls with other offices. There are two types of Employees in Amazon i.e. 'Testers' and 'Developers'. Manager of Amazon don't want any 'Tester' and 'Developer' to sit in nearby cubical office, it means there should not be any shared wall between two 'Testers'/'Developers'.
Input:- First line consist of an integer n, which is number of common walls.
Next n lines consist of 2 integers a and b, which represents the Office Number between which the wall is being shared.
Output: - Print 'Yes', if condition of the manager can be satisfied and print 'No' if not.
Example: -
1-2-3
|
4
Office number 2 is sharing its 3 walls with Office 1,3 & 4.....that is why if Office 2 has a 'Developer' than Office 1,3 & 4 cannot have any 'Developer'.
INPUT:-
3
1 2
2 3
2 4
Output: -
Yes
Any better approach then DFS i.e. O(V+E)..??
Search in a row wise and column wise sorted matrix
Give some practical applications of binary search trees
given a bst, find the in-order successor of a given node. th nodes dont have a pointer to parent
Given a log file from a website which contains the user ID and the accessed URL, find the TOP "sequence" of 3 urls amongst ALL visitors of the website. The sequence of urls have to be in sequence as they are accessed.
My solution is Two hashtables and one MaxUrl object. One hashtable<String,String> userName as key and url sequence as value, where url sequence is three url contatenated by a special character like '#' (google#amazon#yahoo). This value is in FIFO manner. For each value, we check with the second hashtable and see if they exist before, if yes, increment the count, if no, insert the new sequence with count set to 0. So second hashtable<String, Integer> url sequence as key and count as value. Keep a curr_Max to store the current max count, when exceeded, updates max_urlSequence.
Any suggestion?
How to design a zoo in oop? Some basic ideas are to have an abstract Animal class and have birds, mammal extend from it. Also have a class called Cages with different size. Zoo will contain a list of animal, list of cages, probably some workers. What else should I add and how could we improve the design? Thanks.
You have two very large binary trees: T1, with millions of nodes, and T2, with hundreds of nodes. Create an algorithm to decide if T2 is a subtree of T1.
Consider in Java arraylist we have mix of int, double, float, string, etc. How will you find if a given index of arraylist have string. No need to worry about generics and type safe.
Consider the following array {1,2,3,4,5,2,5,4,4};
In the above array, index 4 could be considered as breaking point where summation of 0 to 4 in the array is equal to summation of 5 to end of array. We need to find the breaking point for the given array. I solved this. But follow up was for this array
{1,0,-1,-1,1};. Mathematically the later array's breaking point is 2.
Let G=(V,E) be a connected, undirected graph. write a program to compute paths in G that traverses each edge in E exactly once in each direction.
Example: If there is a Graph with edges in a triangle form V1, V2,V3 we need to display all the paths from V1-V2-V3-V1 , V1-V3-V2-V1
Note: Graph can have any number of nodes and there is no source or destination node given as input.
Given three strings s1, s2 and s3. Check whether s3 is an interleaving of s1 and s2
There is a large file( 1TB) containinig braces. Question is to check for their balance. I said will use a counter, will increment on an open brace and decrement on an close brace. If counter goes negative or counter is non zero at the end of the file, braces are not balanced. Otherwise balanced. Followup question was to make this process parallel ( meaning to see if this problem can be solved through parallelism, like dividing the the problem into sub problem....) Remember the file is very large.
design a data structure for caching the result of "int getSmallestBiggerPrime(int)" so that the client side can reduce the trips to the server as much as possible. There are some examples in format of input->output: 1->1, 2->2, 3->3, 4->5, 5->5, 6->7, 7->7, 8->11, 9->11...
The interviewer did not say whether to use Least Recently Used (LRU) or Most Recently Used (MRU). But he gave a requirement using an example, suppose the user inputs 6 and gets 7 last time, the next time when he inputs 7, there should be no server trip to get 7 as the result.
Given a binary search tree, design an algorithm which creates a linked list of all the nodes at each depth (i.e., if you have a tree with depth D, you’ll have D linked lists).
Imagine we have a large string like this "ABCBAHELLOHOWRACECARAREYOUIAMAIDOINGGOOD" which contains multiple palindromes within it, like ABCBA, RACECAR, ARA, IAMAI etc... Now write a method which will accept this large string and return the largest palindrome from this string. If there are two palindromes which are of same size, it would be sufficient to just return any one of them.
You are a cashier, and any item purchased in the store is in the range of 1c to 99c . Customer always pays 100 c i.e 1$. You need to deliver change with 25c, 10c,5c ,1c.
1. Code to get the most optimal solution with lease number of coins used
2. Some time in India 1 Rs = 150 ps and following coins were available {50,25,20,10,5,2,1}. Here if the change was 40, you should display 2 20ps and not 25ps,10ps,5ps. . What are the optimizations you will make
Given a 3-D array, if any m[r][c][d] is <=0 mark all the cells in the entire row,col and depth as zero and return the o/p array
Design event system, that is receiving events from various client (iPad,mobile,browser) across the world. It is getting approx 1 billion events /day. At any point of time the PM comes and says , retrieve how many events occurred in last 60s and we should be able to retrieve that
There is a king, who has got 1000 bottles of Rum with him, of which One bottle contains poison. And he has any number of slaves. He has got 1 hour to decide which bottle contains Poison, and any slave who even takes a sip of the poison, dies within an hour. How many least number of slaves does the king need to use, to make out which bottle contains poison.
You need to write this program again, without using any library methods. Take the following inputs from user and print the following output.
1 1
1 11
0 011
1 0111
0 00111
0 000111
0 0000111
i.e if user types 1 then 1 will be at printed right shift, and 0 will be printed left shift.
Note: There is no definite count of number of Inputs user wants to give, or sequence of inputs user wants to give. User can give any number of inputs, and it should display the result as above.
You have got 2 strings(S1, S2) and 1 character(c1). All inputs to be taken from user. You need to check for the character c1 in String S1, and wherever you find the character, you need to replace it with the string S2.
Next Write all possible test cases to test the program.
It can be possible that the character c1 is appearing more than once in the String s1.
Clause - You are not allowed to use any Java Library methods in it. Not even charAt() method.
There is a website, which is working fine in US, but not working in India. Debug the scenario.
You have a Movie file, which is not getting played in VLC player. Debug the scenario.
5! = 5 * 4 * 3 * 2 * 1 = 120 (it contains 1 zero).
How many zeroes will be contained in 100! then.
Explain with logic.
How will you test Photo upload feature in facebook, to a Newly created album, to an already existing album, as a standalone photo. Write all negative test cases as well.
A company has developed a browser. The browser has a Private browsing mode, like Incognito mode in Chrome browser. How will you test that browser on a mobile. Write all possible test cases for it.
One can serialize a BST by storing its in-order plus one of pre-order or post-order notations. what makes in-order mandatory?
Given an unordered array of positive integers, create an algorithm that makes sure no group of integers of size bigger than M have the same integers.
Input: 2,1,1,1,3,4,4,4,5 M = 2
Output: 2,1,1,3,1,4,4,5,4
please help me out!!..Its not striking me.
Ramesh and Suresh get a box full of five stars on lottery each. Since both the boxes need not have the same number of chocolates, they decide to play a game. The winner gets to have both the boxes of chocolates. They play alternatively and Suresh starts the game. Given the number of chocolates in both the boxes, let them be c1 and c2, the player takes either c1 or c2 number of chocolates and divide the remaining box of chocolates to two boxes (these two boxes need not have the same number of chocolates). The player who cannot make such a move loses. Input
First line of input contains a number T(1<=T<=1000), the number of test cases. Then follows T lines each containing two space separated integers c1 and c2
(1<=c1<=c2<=10000).
Output For each test case print "Ramesh" or "Suresh" depending on who is the winner.
Input: 2 3 1 4 5
Output: Ramesh Suresh
How would you synchronize a linked list across multiple computers. If nodes are added/removed to a linked list on one computer, all others must reflect this change. Concurrancy must be accounted for. (java)
Given a tree, generate all paths. Note : all paths..not just the ones starting from root
Bag-of-words model. Write the process of search based on inverted index. The follow up is given some attributes(an array), how to filter the search result.
Implement a function which returns list of all nodes in a binary tree having a given number of leaves, say k . Also mention complexity.
Find all the repeating sub-string sequence of specified length in a large string sequence. The sequences returned i.e. the output must be sorted alphabetically.
For e.g.
Input String: "ABCACBABC"
repeated sub-string length: 3
Output: ABC
Input String: "ABCABCA"
repeated sub-string length: 2
Output: AB, BC, CA
Given a set of intervals, how to find the interval with maximum number of overlaps (not the length of the overlap).
Given a sorted (increasing order) array, write an algorithm to create a binary tree with minimal height.
Replace each node with the sum of all greater nodes in a given BST?
How will you Serialize and Deserialize the binary tree?
First find out the number 1's in the binary digit of a given integer. Then find out an integer which is greater than the given integer and contains same number of binary 1's
Given a directed graph, design an algorithm to find out whether there is a route be-
tween two nodes.
What is the complexity of the algorithm?
Find the shortest path in a maze (from origin to destination). I believe we are supposed to use Dijkstra or BFS. But what I am confused with is that Dijkstra computes the shortest path based on the distance of each edge. But a maze doesn't have weighted edges, and its shortest path should be 'minimum number of cells'. How can we make use of Dijkstra, or BFS?
Given a tree (Not a binary tree) and two nodes A and B, node has parent and child properties find the path P from A to B (In a tree there is only one path). Reduce the complexity to O(P).
Given an integer array find all pythogorean triplets. a^2 + b^2 = c^2 print the a,b,c and their indexes
Determine whether an interger is a multiple of 5 in O(logn) time complexity. You cannot use / and %.
The final question was just how to write a connection pool (i.e, a class that returns connections to the user, and if the user is done, returns them back to the pool)
Difference between cloning a directed graph vs undirected graph. There are lots of tutorials on how to clone a directed graph online, such as leetcode. But what if it's undirected graph? It appears to me that it would be pretty much the same? For example,
public class Node() {
public int data;
public ArrayList<Node> adjacent;
}For example, A can have a neighbor called B. Therefore, we may traverse from A to B. For undirected graph, does it imply that B can always traverse back to A? Even if it does, if we use a hashtable to keep track of which node has been copied and processed in the queue, then the logic for cloning a directed graph should be the same as for a undirected graph, right?
Find the LCA (least common ancesstor) of k nodes of a given binary tree. Later extend this for n ary tree.
Given a Binary tree and a arbirary node of that tree , find all the nodes at a Distance of K from that Node .Nodes DON’T have parent pointers
Does a given file name match a single-star pattern? (can't use regex I assume)
index.html matches *.html
foo.txt does not match *.html
matches(“index.html”, “*html”) returns true
matches(“foo.txt”, “*html”) returns false
matches(“cat”, “c*t”) returns true
Given a set of intervals (time in seconds) find the set of intervals that overlap. Follow-up: what if we were to find the interval with maximum overlap.
Given a set top box:
a, b, c, d, e,
f, g, h, i, j,
k, l, m, n, o
p, q, r, s, t
u, v, w, x, y
z
Write code to give the character sequence given a word, For example, if the word is "CON", the function will print this:
Right//now we're at B
Right//now we're at C
OK//to select C
Down
DOwn
Right
Right
OK//to select O
Left//now at N
OK//to select N
note: Be careful when you're at Z. if you go to the right, you will get stuck.
Afterwards, the interviewer adds a space to the right of 'Z' to test the code.
How do you design a Maze and what kind of data structures you use for Maze. In addition, write a method to print the shorted path from start to end point.
Design Short URL. (I am not sure what it even means)
Given two Binary trees. these trees "may" have right and left branches swapped. Now compare it.
Given a undirected graph, clone it. Now if the undirected graph has the neighbors with the nodes as same data - how do you make sure you create the exact same branches and also how do you make sure you don't run into loops for the exact node. He gave a empty directed graph and asked me write code after that.
{Ques.. Sum of nos. nos. like(very very long no.s)
A=123456278798238093532765432662476427646456353425635454854
B=1234562787982380935327654326624764276464563534248758758756
C=123456278798238093532765432662476427646456353425634436746432}
there are a million nodes, it is a DAG, a startpoint is a node with no edges into it and an endpoint is a node with no edges out of it. Each query asks the question - is there a path between a specified pair of start and endpoint nodes. To perform a thousand such queries on a graph that has million nodes, using DFS/BFS is order (1000 * 1000000). I was asked for a solution with better runtime than that.
Sink Zero in Binary Tree. Swap zero value of a node with non-zero value of one of its descendants
so that no node with value zero could be parent of node with non-zero.
Given an array of +ve as well as -ve numbers, find out whether it is possible or not to convert it to 0 by adding/subtracting operations on all the elements.
e.g arr[]={1,2,3}
YES (1+2-3)
arr[]={3,6,2}
3+6-2 != 0
3-6-2 !=0
-3-6-2 !=0
-3-6+2 !=0
-3+6-2 !=0
-3+6+2 !=0
3-6+2 !=0
3+6+2 !=0
Hence ans= NO
Write a Program that takes an array of integers representing the heights of the trees in the row as input and prints the list of the visible trees.Given a table of the form:
Product Sold on
A 1/1/1980
B 1/1/1980
C 1/1/1980
A 1/1/1980
B 1/1/1980
C 2/1/1980
A 2/1/1980
There are 30 products and 10,000 records of such type. Also the month period during which sales happened is given to u.
Write the program to display the result as:
Product Month No. of copies
A January 12
A February 15
A March 27
B January 54
B February 15
B March 10
C January 37. We need to write the function to check the password entered is correct or not based on the following conditions..
a) It must have atleast one lower case character and one digit.
b)It must not have any Upper case characters and any special characters
c) length should be b/w 5-12.
d) It should not have any same immediate patterns like
abcanan1 : not acceptable coz of an an pattern
abc11se: not acceptable, coz of pattern 11
123sd123 : acceptable, as not immediate pattern
adfasdsdf : not acceptable, as no digits
Aasdfasd12: not acceptable, as have uppercase characterWrite a function to check if two rectangles defined as below, have common area or not. The functions take the top left and
bottom right coordinate as input and return 1 if they have common area, otherwise return 0.
// you can write your additional functions here
int doesRectOverlap(rect ra, rect rb){
/* For your reference
struct rect{
int topx,topy,botx,boty;
};
The above has already been declared please do not redclare */
There are 10,000 balls and may be 500 different colors of ball
Example: There are:
4 - red ball
5900 - Blue ball
3700 - Green ball
396 - mintcream ball
Or there may be 10,000 red balls.
Or all balls are has same range, i.e. 500 red, 500 blue, etc.
We don’t know the range of any ball and number of color balls, but the minimum is 1 color and maximum is 500 colors, and we have auxiliary array of size 500. how to arrange all same color ball together in minimum passes over balls? is it possible to do in less than two passes ??
Input : a1,a2,...,an, b1, b2, ..., bn
Transform it to a1, b1, a2, b2, .... an, bn.
It has to be done in-place
There are 10,000 balls and may be 500 different colors of ball
Example:-there are
4 - red ball
5900 - Blue ball
3700 - Green ball
396 - mintcream ball
Or there may be 10,000 - red ball
Or all balls are has same range means 500-red,500-blue and so on..
We don’t know the range of any ball and no of color ball but minimum is 1 color and max is 500 color of ball and we have auxiliary array of size 500. What will be the time complexity to arrange all same color ball together??
{write a function to give demostrate the functionality of 3D matrix in 1D matirx.function prototye: void set (int value,int indexX,int indexY,int indexZ, int [] 1dArray);void get (int value,int indexX,int indexY,int indexZ, int [] 1dArray);}
There's a matrix. Each element in the matirx is a bit (0 or 1). Write a method to reverse this matrix. The matrix is stored in a one dimensional char array. The length of each row is given.
How do you improve your solution when handling large amount of data?
A chessboard was given to us. Where in there was a Knight and King was placed oncertain positions. Our aim is to reach the king from the knight in minimum no of counts.As we know, knight can either move 2 steps vertical/horizontal and 1 stephorizontal/vertical. same goes here as well. Proper image of the chess board was given inthe question paper, and all the positions(max 8) were given that knight can take in thefirst step. Sol : Most of us implemented using recursive funcSeat Reservation prog for the theatre. Write a function for seat allocation for the movietickets. Total no of seats available are 200. 20 in each row. Each row is referred by theCharacter, "A" for the first row and ,J, for the last. And each seat in a row is represented by the no. 1-20. So seat in diffrent rows would be represented asA1,A2....;B1,B2.....;........J1,J2... Each cell in the table represent either 0 or 1. 0 rep wouldseat is available , 1 would represent seat is reserved.Booking should start from the last row (J) to the first row(A). At the max 20 seats can be booked at a time. if seats are available, then print all the seat nos like "B2" i.e (2 row, 3col) otherwise Print "Seats are not available." and we must book consecutive seats onlysuppose u r given a 4*3 rectangle like (take these values from user)Now u have to calculate the no. of squares in this rectangle like:No. of squares of dimension 1 is 12No. of squares of dimension 2 is 6No. of squares of dimension 3 is 2No. of squares of dimension 4 is 0Total no. of squares are 2suppose u r given a 4*3 rectangle like (take these values from user)Now u have to calculate the no. of squares in this rectangle like:No. of squares of dimension 1 is 12No. of squares of dimension 2 is 6No. of squares of dimension 3 is 2No. of squares of dimension 4 is 0Total no. of squares are 2
Test cases for int rand() which returns a random number between 0 - 999
Given a number give its english form
1-> One
999 -> Nine hundred and ninety nine
Max number is: 999, 999, 999
Design a webservice which would take a word, and return all anagrams
Given a graph that where A->B indicates that node A should be processed before processing B. Design an parallel algorithm to process all the nodes
Smart pointers, how are they implemented. Any usecase for using smart pointers in languages that already have garbage collectors
Design a voicemail system. Would you use RDBMS or File system, provide rationale.
An application is crashing the moment it is opened, how would you test it.
How do you add two numbers that are larger/longer than Integer datatype? I said I would use BigInteger , then he asked how will you add if the number is larger than BigInteger?
Implement Stack operations using two queues. I wrote some code, later he asked, how many elements could be added to this queue. (My code was like this Queue<Integer> q1 = new Queue<Integer>(); ) What would be the maximum number of elements that this queue would accomodate? My code was in java.
Design a object oriented class for a vending machine. My idea is that it should have the ability to take in money, item selection, serving item. But I am not sure how to put everything together using good object-oriented principles.
Increment a integer array with value between 0-9
Ex:
input [1,2,3]
output [1,2,4]
Lowest common ancestor binary tree.
1) Given left() right().
2) Given just parent()
3) Increase the performance to o(logn) with parent().
Print a tree in Zig zag order.
Design question to find the most frequent sequence of web page views from a log file of all the web pages viewed. Say the sequence is 4.
Arranging file system in the form of a binary tree. I think the interviewer meant B-Tree. She had a huge accent.
Implement a method that flattens an iterator of iterators. I believe we will need a class to do it? Java preferred. Thanks.
Given a list of integers that fall within a known short but unknown range of values, how to find the median value?
Some say we could use selection algorithm. But that will take O(n/2 * n), which results in O(n^2). I don't know how it is a good solution.
A graph contains one start node with no out-edges and a ending node with no in-edges. Such graph contains, say 10 million nodes. Question is how to find out effectively if two nodes are connected. The graph is a directed, unweighted and acyclic graph.
Additional Information : the graph will be queried for such connectivity queries at least a million times.
I was able to come up with building a transitive closure. But the space requirements ( O(10million * 10 million ) is huge.
2) I suggested BFS but it would be O( million * 10 million ), so that also was rejected.
Is there any other effective way ?. Practically I couldn't think of any other way.
Write a method which takes an array input and returns true if the sum of any two elements is equal to the sum of the corresponding indices. Like if for an array the sum of values at any two indices i and j is equal to the sum of i and j.
I can't think of any other way to do it except brute force.
Implement classes for a website that can be used for building your own computer in object-oriented design manner. Eg: If a user selects a motherboard, it should filter out all the incompatible CPUs etc. You have to implement various classes that can be used for implementing this functionality. Java preferred.
Thanks a lot.
How do you write a custom error handler in Java?
what happens when you re-throw an exception in Java?
How would you design a database to store directory type data structure (e.g. windows folder containing subfolders)?
What is SOAP? What is REST? What are the major differences between SOAP & REST?
What is a process? what is a service? what are the differences between a process and a service (e.g. in windows)?
What is a static method? What is the difference between instance method and static method?
What is an interface? How is an interface different than inheritance? Why multiple inheritance not allowed?
What is generics? How do you call a generic method in C++/C#? What are the disadvantages of generics?
You are responsible for maintaining a web service that sits behind a load balancer. If the web service starts failing, how will you go about fixing it?
Design "YOU TUBE".
Like how do you upload/where to do you upload/how do you fetch/ how millions of incoming requests will be addressed.
Also take care of things like how do you provide services.
You are given two version numbers of a software, like Version 10.3.4 and Version 10.3.41. Write a program in Java to find out which of the version numbers are the latest. If version 1 is latest output -1, if version number 2 is latest output +1 else output 0 if same version. Both the version numbers are taken as string.
In given array find zero and replace the entire row and column with zeros
E.g Input:
1 2 3 4
5 6 7 8
9 10 0 11
12 13 14 15
Output:
1 2 0 4
5 6 0 8
0 0 0 0
12 13 0 15How to sort 2 queues without additional containers?
Write a function that takes n parameters and returns an n-dimensional array using those parameters as the dimensions. The main problem is implementing k loops, where k is an unknown.
How to implement a Least Frequently Used (LFU) cache?
Least Frequently Used (LFU) is a type of cache algorithm used to manage memory within a computer. The standard characteristics of this method involve the system keeping track of the number of times a block is referenced in memory. When the cache is full and requires more room the system will purge the item with the lowest reference frequency.
What would be the best way to implement a most-recently-used cache of objects, say in Java?
I've already implemented one using LinkedHashMap(by maintaining the no. of times objects are accessed) But I'm curious if any of the new concurrent collections would be better candidates.
Consider this case : Suppose cache is full and we need to make space for another one. Say two objects are noted in cache which are accessed for one time only. Which one to remove if we come to know that other(which is not in cache)object is being accessed for more than once ?
Thanks!
write a program to convert a number in indian rupees form such that we input 11200234
then output come 1,12,00,234 in c language
pls help
Find the pair of numbers that sums to an integer k from an linked list.
Q: Given an array of integers and an integer k. Returns the pairs that subtract result in k. Example: 3,6,10,13.
(3,6),(10,13)
find a cycle in the given array and return the length of a cycle
for example, a[0] = 2, a[1] = 0, a[2] = 3, a[3] = 1, a[4] = 2, a[5] =4;
a[0]=2 -> a[2]=3 -> a[3]=1 -> a[1] =0 -> a[0]=2 ....
2->3-1>0->2->3->1->0->...
so return value should be 3.
Program an iterator for a Linked List which may include nodes which are nested within other nodes. i.e. (1)->(2)->(3(4))->((5)(6). Iterator returns 1->2->3->4->5->6
Given a line length insert white space so text is uniformly displayed within the given length
What is mean by non blocking thread safe? Is it different from thread safe blokcing? Code a non blocking thread safe queue in Java
You have given a number, rearrange the digits of given number and find the next large number.
For example given number is 2576
the next large number is 2657
code is not required approach or algo is enough.
Mapping
'1' = 'A','B','C'
'2' = 'D','E','F'
...
'9' =
input: 112
output :ouput = [AAD, BBD, CCD, AAE, AAF, BBE, BBF, CCE, CCF]
Group Anagrams
input = ["star, astr, car, rac, st"]
output = [["star, astr"],["car","rac"],["st"]);
You are given an array / sequence of colors. In this sequence / array, find a couple (both colors adjacent to each other) which are same color. Now, remove that pair. Now, after this removal, if there are further couple of same color then remove that as well and so on.
For a given array / sequence of colors, find the maximum number of couples.
For eg., consider following array of colors :
R G B B G R Y
1. BB is one couple, so remove it :
R G G R Y
2. GG is one such couple after removing BB, so remove it :
R R Y
3. RR is one such couple, so remove it :
Y
So, the maximum number of couples is 3.
Input :
Y R G G R R G G R Y
Output :
5 (maximum number of couples)You are given a matrix. Starting from [0, 0], you have to move over the matrix in clockwise-spiral direction, i.e., we start from [0, 0], move upto [0, 4], and then move to [3, 4], then move to [3, 0], then move to [1, 0], then to [1, 3] and so on.
Move in this way and print all the elements.
Input :
1 2 3 4 5
6 8 9 a b
c d e f g
h i j k l
Output :
1 2 3 4 5 b g l k j i h c 6 8 9 a f e dGiven a 2D array of 1 and 0, Find the largest rectangle (may not be square) which is made up of all 1 or 0.
You are given an array, divide it into 2 equal halves such that the sum of those 2 halves are equal. (Imagine that such division is possible for the input array and array size is even)
Given an integer, find the next highest and next lowest integers, with equal number of 1s in their binary representation as the original number.
Suppose you are given a set of small boxes, numbered 1 to n, identical in every aspect except that each of the first i contains a pearl whereas the remaining n-i are empty. You can have two magic wands that can each test if a box is empty or not in a single touch, except that a wand disappears if you test it on a box that is empty. Show that, without knowing the value of i, you can use the two wands to determine all the boxes containing pearls using at most o(n) wand touches. Express as a function of n, the asymptotic number of wand touches needed.
Stakeout
Congratulations! You are the new elite hacker in a group of villainous ne'er-do-wells.
Luckily this group is more saavy than your last band of ruffians, and they are looking to software (and you) to improve their take. The con man for the team, has gone door-to-door down each street posing as a termite inspector so he could covertly total the valuable goods in each house. Normally the gang would just rob all the valuable homes, but there's a catch! Whenever a house is robbed in this wealthy neighborhood, the police watch it and the neighboring houses for months.
So the gang can't simply rob all the homes, and if they choose to rob one, they can no longer rob the house on either side of it.
The ringleader wants to know what houses he should rob to maximize the team's profit, and he wants to know now. Write a function that takes in an array of positive integers (home values) and returns the maximum expected value of robbing that street.
For example:
[ 20, 10, 50, 5, 1 ] should return $71, as robbing the first, third, and fifth houses is optimal [ 20, x, 50, x, 1 ]
[ 20, 50, 10, 1, 5 ] should return $55, as robbing the second and fifth houses is optimal [ x, 50, x, x, 5 ]
Write a function which verifies a binary tree where all leaf nodes are at the same level.
Online assessment:
There are N points on a 2D plane, find the k closest points.
i am working on project and we want to access ASCII value of string at some index But we don't want access chat at index and parse it to integer
Example:- char character = s.charAt(8);
int ASCII = (int) character;
is there any other way to do same without converting to char?? and what will be time complexity? is there any built in function in java ? i don't know how char store in memory please anyone can explain me ? and how to handle Unicode without converting to char ??
Thanks!!
You are given an array of integers, sorted, but rotated. Find an better than O(n) algorithm to find an element in an array. Write code for this.
BST - find next immediate higher value
Ex . BST 2,3,6,9,7,4,13,24,19
find immediate highest value for 9 should be 13
BST - find next immediate higher value
Ex . BST 2,3,6,9,13,24,19
find immediate highest value for 9 should be 13
Given String ss = "(a(b))(c(d(f))g)(y(h))
Find the max depth of parentheses. Result should be numeric like here result should be 3 as "f" is surrounded by 3 parentheses.
You are given a long list of integers, so long that you can not fit the entire list into memory, implement an algorithm to get the max 100 elements in the list.
Given an array of integers and the target as an input E.g.
input = {5,2,1,4,3,6,7,8} .. target : 333 it should true as (5 +214 + 36 + 78) if the target does not match it should return false.... Eg. of false input : {5,5} target:60 ... It should return false as the combinations possible are 5+5 = 10 and 55
Consider an array which may contains the alphabets from A to Z.
suppose consider the below examples
A[9] = {A,C,D,G,D,E,A,C,A}; then the output should be in the format of A=3;C=2;D=2;E=1;G=1
A[9] = {A,B,D,C,D,B,A,B,A}; then the output should be in the format of A=3;B=3;C=1;D=2
write the logic in C. the values in array may vary. the output should count the alphabets in the array
Two container of 5 L and 3 L are given. Then are is 9.5L water given you need to make 4L water with minimum attempts and water wastage.
Debugging testcases if a video file is VLC is not opening along with another scenario where only voice is playing not video.
Debugging testcases if a web site is opening in US but not in India
Imagine a binary tree lying on the floor with nodes as balls and edges as threads, you are given a pointer to a node. When you pick the tree from that node up what will be the structure of the tree. You have gravity changing the structure of the tree
write Fibonacci series with recursion.
how you will design directory so your search will faster, provide solution so my search time is efficient.
you have array of n size having numbers between 1 to 100. you need to provide algorithm for sorting array with BigO(n) iteration.
Second question is Implement a boolean method for returning whether an appointment with a doctor is possible or not. Given that we have a set of start and end time frames already scheduled with the doctor.
Find the longest common substring between 2 string in O(n) complexity
class NoName
{
children = new Hashtable()
name = ""
boolean hasChild(child: string)
{
return this.children.hasKey(child)
}
NoName addChild(child: string)
{
var childnode = new NoName()
childnode.name = child
this.children[child] = childnode
return childnode
}
NoName getNode(child: string)
{
if this.hasChild(child)
return this.children[child]
else
return this.addChild(child)
}
void addList(input: string)
{
var currentNode = this.getNode(input[0])
input = input.SubString(1, input.Length ? 1)
if (input.Length < 1)
currentNode.getNode("")
else
currentNode.addList(input)
}
string scan()
{
if (this.children.Values.Length == 0)
return this.name
if (this.children.Values.Length == 1)
return this.name + this.children.Values[0].scan()
var temp = new Array()
foreach(child in this.children.Values)
temp.Add(child.scan())
return this.name + "{" + temp.Sorted().JoinArray(",") + "}"
}
}
var x = new NoName()
x.addList(’/home/user/foo’)
x.addList(’/home/user/bar’)
x.addList(’/home/user/baz/one’)
x.addList(’/home/user/baz/two’)
print x.scan()Is there anyone can help me translate these code to java or tell me the result ,I will really appreciate it.Thanks
There is a matrix which contains white cells , black cells and only one gray cell, need to go from (0,0) to (N-1, N-1) if Arra[N][N]
constraints:
a. The path should cover only white cells and should go via grey cell.
b. The node once visited cannot be visited again.
White cells are represented by 0, black cells by 1 and grey cell by 2.
Java preferred.
I know there is another thread on the same problem, but apparently nobody has the correct solution there. Most of the suggested solution won't cover all cases.
Print a 2D array in spiral order.
Given a 2d array N*M made of only 1's and 0's . I need to find a maximum subarray(square or rectangle) between two rows of the given 2d array which has all ones inside it. I need to find count of ones in this maximum subarray
EXAMPLE : Let N=4 and M=5 and the array be
1 0 1 1 0
1 0 1 1 1
0 1 1 1 1
0 0 0 0 1
Now if their are Q(say here it be 2) queries each describing upper and lower row between which we need to find this subarray.
Query 1 : 1 1(means start at row 1 and end also at row 1).Then we can clearly see answer will be 2
Query 2 : 2 3(means start at row 2 and end at row 3).Then answer will be 6 here.
Now,if queries can be very large in number(say upto 10^6) .How to tackle this problem
You are standing at 0 0 and you have to get to i, j. Find the number of ways. Did that with recursion then with DP. Then he extended the question saying some edges are not traversible. Then edges have weights, find min weight path.
You are standing at 0 0 and you have to get to i, j. Find the number of ways.. Then he extended the question saying some edges are not traversible. Then edges have weights, find min weight path.
An array is given representing the colors of n jars, colors have values 0-99. When two jars are mixed the resulting volume is same as volume of one jar. Smoke is color1*color2… and resulting color is (color1+color2)% 100. Keep on mixing colors such that you end up with just one jar with minimum smoke.
Write a business_days_from_now() method, which takes as an input a number of business days, and returns a Date object which is that many business days from now. For this, a business day is only a weekday and not a weekend.
for example:
Today is Wednesday the 8th.
business_days_from_now(5)
Current Date: Jan 8, 2013 Wednesday
Output:
Wednesday the 15th
Second Question is to Encode a String
aaaabbccdd -> a4b2c2d2
In minimun space and time complexity
First question is You have two numbers represented by a linked list, where each node contains a single digit. Write a function that adds the two numbers and returns the sum as a linked list
Implement stack with findMiddle and deleteMiddle() in constant time.
Can you please explain and write code for it
//Online Coding Assignment
As a member of the cab finder app team, you are tasked with implementing a CabFinder class that has the following minimal public interface:
class CabFinder implements CabStatusListener {
/**
* Initiates CabFinder. Called only once per app startup.
* @app An application object providing services implemented by
* the rest of the application.
* @maxCabs Nearest number of cabs that can be returned to the user
*/
public void initialize(CabApp app, int maxCabs) {
//Insert code here...
}
/**
* Gets nearest cabs within 1km of the current user’s location.
* These must be the *nearest possible* @maxCabs in the 1km area.
* @return An unordered list of the nearest cabs.
*/
public Cab[] getNearestCabs() {
//Insert code here...
}
/**
* Asynchronous Callback per CabStatusListener (see below). Called when the position of a cab has changed.
*/
void onCabPositionChanged(Cab cab) {
//Insert code here…
}
/**
* Asynchronous Callback per CabStatusListener (see below). Called when a cab’s availability changes.
* @cab The cab whose availability has changed
* @isAvailable true if the cab is now available, false otherwise
*/
void onCabAvailabilityChanged (Cab cab, boolean isAvailable) {
//Insert code here…
}
}Supporting Classes:
Here are the classes and utilities that are available for your use (you are not required to write any implementation for these classes)
/**
* Coordinates on a 2D map with a one meter granularity.
*/
class Position {
public int x;
public int y;
}
interface Cab {
/**
* Unique identifier of a cab.
*/
int getID();
/**
* Gets the current position of the cab
*/
Position getCabPosition();
/**
* Returns whether or not the cab is available
*/
boolean isAvailable();
}/**
* Provides services implemented by the rest of the Cab Application.
*/
interface CabApp {
/**
* Gets the current location of the user
*/
Position getUserPosition();
/**
* Returns an iterator that gives access to the list of all cabs in the city
*/
Iterator<Cab> getCabs();
/**
* Registers a CabStatusListener object for change notifications of cab object data.
*/
void register(CabStatusListener listener);
}
/**
* The CabStatusListener interface
*/
interface CabStatusListener {
/**
* Called when the position of a cab has changed.
* @cab The cab object
*/
void onCabPositionChanged(Cab cab);
/**
* Called when a cab’s availability changes.
* @cab The cab object
* @isAvailable true if the cab is available, false otherwise
*
*/
void onCabAvailabilityChanged (Cab cab, boolean isAvailable);
}
How would you model the animal kingdom (with species and their behavior) as a class system?
How would you model the animal kingdom (with species and their behavior) as a class system? Java
How to find the adjacent elements of an single dimensional array whose difference is 1; What is the Time Complexity & Auxiliary Space you use ? What type of efficiency can be achieved?
How to sort an single dimensional array whose elements are {4,5,6,4,5,6}; What is the Time Complexity & Auxiliary Space you use ? What type of efficiency can be achieved?
Implement entity tag cache in following two assignments. Design cache for
read performance. Also, ensure that it takes as little memory as possible.
Write a caching class EntityTagCache that is supposed to cache tags for a given
id. Also provide TestEntityTagCache JUnit class that we can use to verify the
functionality. We only need above two files ( e.g. no need for build file ), as
we'll go through your solution in an Eclipse Java project.
An entity and its tags have following characteristics:
- A given entity is identified by an int id. The id is >= 0.
- An entity can have 0-N tags, where each tag is a string value. E.g. for
id '1', we can have tags like 'foo' & 'bar'. There are around 1000 unique
tags in 100 million entities, but the actual number can vary by a few thousand.
- The EntityTagCache does not need to consider id/tag eviction. It is expected
for the cache to throw a OutOfMemoryError if more tags exist than we can cache
in memory. However, the design should ensure that it takes as little memory
as possible to cache the tags.
- There can be maximum of 100 million entities in the cache and the id value
cannot be more than the number of entities in the cache and is >= 0. Thus,
if we've to cache 100 entities, then id is from 0 to 99.
- We should be able to load our initial data into the cache when we create
EntityTagCache. We should pass a file to the cache that contains entity
information. E.g.
entities.csv
------------
1,foo,bar
2,abc,foo
3
4,xyz,bar
In above, in first line entity id is 1 and tags are foo, and bar. For entity id 3
there are no tags.There are four unique tags 'foo', 'bar', 'abc', and 'xyz'.
EntityTagCache cannot be updated once it has all the data. Also, it
does not need to have any notion of eviction, as we require that all the
data must be loaded in memory. The cache only provides the following
public method:
1. 'getTags' method that takes an id and returns the tags for the entity.
This method on worst case ( barring garbage collection) take a few
100 nano seconds. It can be called 1000's of time in a few milliseconds.
The cache should be designed for multi threaded access with 1000's
of requests to getTags in a few ms.
Design database locks to allow r/w concurrency and data consistency.
Threads synchronization methods, how do they use CPU time slice and compare their efficiency?
you are given a log file with userid, login time and logout time . The login/logout times are in terms of integers .
When given a time range with a difference of 1 i.e. (1-2) or (2-3) return how many users are online
Given an array of integers, return the maximum subsequence subset and the sum formed by the subset
Using the symbols of Periodic table, return the longest word possible from the english dictionary
A Contracter is doing work for 7 days at your home, you need to pay him 7000$ in total. Every day you need to pay him 1000$ only .. To Pay him you have a gold plate wortjh 7000$ , but you can cut it only twice
Design LRU Cache
Design Service like tinyurl
Start with the sequence of non-zero digits 123456789. The problem is to place plus or minus signs between them so that the result of thus described arithmetic operation will be 100.
How would you model the animal kingdom (with species and their behavior) as a class system?
How would you model the animal kingdom (with species and their behavior) as a class system? (Java)
Given a list/array of names(String) sort them such that each name is followed by a name which starts with the last character of the previous name.
# input
[
Luis
Hector
Selena
Emmanuel
Amish
]
# output:
[
Emmanuel
Luis
Selena
Amish
Hector
]
Given a set of names, sort them in the following manner the next word should start with the last letter of the previous word. Java ?
How will you implement run-time polymorphism in C? There are two structs. There is a common function receiving only one argument(only one). The function should accept both base struct and derived struct objects and do corresponding actions. i.e if base struct object is passed, do base struct's task and vice versa
The interviewer asked the following question.
char *s = "Hello";
printf("%s",s);
printf(s)The second print statement crashes sometimes. Why
Design a Logging mechanism. Should be thread safe.
Initially i came up with Command Pattern, and write into a File. Was asked how i will synchronize multiple threads writing into Same File?
Later he gave hint about Aspect-oriented Programming(AOP). And also he gave a hint of Not always writing into the File, can also be a Mail,etc..
Write all test cases and Test data to test BODMAS rule in Maths.
You are given a 3 * 3 Matrix -
3 -5 10
6 2 -1
2 6 1
Q: Find the sum of the elements of each rows, and each column, and then display row number \ column number having the maximum sum and the minimum sum.
Given a binary search tree whose nodes are integers, find the frequency of occurrence of each digit in the tree.tr
Minimum Spanning Tree using alghoritm prim
You have a single string which contains all the positive numbers upto N concatenated together. If you are given an input number then how would you find the index position of the number in the string.
Eg:
String str = "12345678910111213141516171819202122232425......upto 10000";
input = 20 should return the index of 20 in the string which is 29The example string is upto 10000. The actual string can be upto any number N.
How would you represent a graph with million nodes ?
Suppose an array contains below values
A = {A,B,C,B,A,C,A,B,C,A} then the output should display in the below format
A=4;B=3;C=3
Could you please send the logic for the above question in C ?
How to find duplicates in an array
There are two questions that I want to ask.
Q1) divide two numbers without “/”
Q2) judge if there are two numbers in an array add to a given number
For both the questions please consider minimum space and time complexity
Given a collection of 3-set sequences, where a 3-set sequence is defined as a list of 3 different pages (for example: mouse-keyboard-printer is a 3-set sequence, while printer-mouse-keyboard is another) accessed sequentially on amazon.com, find the most common 3-set sequence with minimum space and time complexity
Write a function to remove all redundant characters in a given string with minimum space and time complexity
You are given an array A with elements 0 to n-1, numbers can be repeated in the array. Create n sets where
S[i]={a[i],a[a[i]],a[a[a[i]]]…}. Set has all elements unique. Find the size of the largest set.
Given a rectangular grid of N*M (1-based indexing) in which their are k monsters on k different cells.Now we need to answer Q queries in which we will be given lowest row number(L) and highest row number(H) we need to tell maximum area of rectangle between those rows that don't have a monster.(Here area of rectangle means count of cells only)
Example : Say we have a grid of 4 * 5 (mean n=4 and m=5) and monsters are located on 7(=k) cells which are (1,3) , (1,4) , (2,1) , (2,4) , (3,2) , (4,1) , (4,2) and let we have 1 query in which L=3 and H=4 then the maximum area is 6 here.
Now if the queries are very large say 10^6.Then how to tackle this problem.Is their any dynamic approach or so for doing it?
int sum = 0;
for (int i = 0; i < m; i++)
for (int j = i + 1; j < n; j++)
for (int k = j + 1; k < l; k++)
sum++;
what will be the value of sum?
Given an array A of n numbers we can perform 3 operations on its array elements.Their are n operations in total and ith operation is to be applied on elements from ith index to last element of the array.
1.Reverse(R) : Reverse the elements from A[i..n]
2.Add(A) : Add X to each element from A[i..n]
3.Multiply(M) : Multiply Y to each element from A[i..n]
Note : In 2nd and 3rd operation all calculations done modulo Z.
I need to find final array after nth operation is done.
EXAMPLE : Say n=3 and array has 3 elements [1,1,1] and lets X=2 ,Y=3 , Z=1000 .If sequence of operation is ARM which means 1st operation is Add,2nd operation is Reverse and 3rd one is Multiply.Then resultant array after final operation will be [3,3,9].
I was needed to calculate this array in efficient manner in c++/java
Can someone provide me with the code of merge sort in which values of more than one array are swapped based on sorting of one array.That is if we have 3 arrays A,B,C and i sort Array A then corresponding values of B anc C should also be swapped!!Please Help!!
You have a directed graph that is quite generic (has disjoint parts, cycles, etc). Please find the first loop you hit when traversing and print the nodes in the loop. Assume data is an integer.
You are given an array of n elements. The elements have are n-bit long too.
Now n here represents the number of employees in a company. Element with index 0 is information about employee 0, at index 1 is information of employee 1....
For each element, the bits represent whether that employee works (not same team... just works) with employee at that index.
Ex. element 0 = 0110 => emplyee 0 works with employee 1 and 2
element 1 = 1001 => emplyee 1 works with employee 0 and 3
...
Put employees in groups in which they work. The transitive property is applicable here i.e. if A works with B and B works with C, ABC will be in one group.
The solution needs to efficient in terms of run time and memory. I hope the above is clear.
What is the output of following program:
1 #include <stdio.h>
2
3 int r = 1;
4 int numbers[5] = {1, 2, 3, 1, 5 };
5
6 int main(int argc, char** argv)
7 {
8 #if !defined(_MSC_VER)
9 asm("leal numbers, %esi");
10 asm("movl $0, %ecx");
11 asm("movl r, %eax");
12 asm("label1:");
13 asm("movl (%esi,%ecx,0x4), %ebx");
14 asm("imul %ebx, %eax");
15 asm("addl $1, %ecx");
16 asm("cmpl $5, %ecx");
17 asm("jl label1");
18 asm("mov %eax, r");
19 #else
20 __asm
21 {
22 LEA ESI, numbers
23 MOV ECX, 0
24 MOV EAX, r
25 label1:
26 MOV EBX, [ESI + ECX * 4]
27 IMUL EAX, EBX
28 ADD ECX, 1
29 CMP ECX, 5
30 JL label1
31 MOV r, EAX
32 }
33 #endif
34 printf("Result= %d\n", r);
35 return 0;
36 }Given an undirected graph with n vertices and m edges. How to check for perfect matching in the graph.(Perfect matching means each vertex has degree 1).Provide a code in c++.
GIven n customers and k rooms in a hotel.Each customer has a starting and ending time and his favourite room.How to schedule them so that maximum no of customers can get the rooms.The time of two customers should not overlap in the same room
eg
4 2
10 100 1
100 200 2
150 500 2
200 300 2
Ans 3 erve the 1st, 2nd and 4th customers, then we can get a maximum of 3.
help me with the logic
prim algorithm determine Minimum Spanning Tree java
prim algorithm determine Minimum Spanning Tree java?help code java
Problem Statement: A child is arranging rocks in layers. He can arrange the rocks, in such way that, any layer has lesser rocks than its base layer. Given n rocks, In how many ways can the child arrange the rocks.
You are given a binary array with N elements: d[0], d[1], ... d[N - 1].
You can perform AT MOST one move on the array: choose any two integers [L, R], and flip all the elements between (and including) the L-th and R-th bits. L and R represent the left-most and right-most index of the bits marking the boundaries of the segment which you have decided to flip.
What is the maximum number of '1'-bits (indicated by S) which you can obtain in the final bit-string?
'Flipping' a bit means, that a 0 is transformed to a 1 and a 1 is transformed to a 0 (0->1,1->0).
Input Format
An integer N
Next line contains the N bits, separated by spaces: d[0] d[1] ... d[N - 1]
Output:
S
Constraints:
1 <= N <= 100000
d[i] can only be 0 or 1f
0 <= L <= R < n
Sample Input:
8
1 0 0 1 0 0 1 0
Sample Output:
6
Explanation:
We can get a maximum of 6 ones in the given binary array by performing either of the following operations:
Flip [1, 5] ==> 1 1 1 0 1 1 1 0
What kind of Environment and Work you are expecting from Amazon?
What fields are contained in a defect report and brief description about each field?
A PDF file is not getting opened how will you debug this issue before reporting it to development team?
List Functional and Non-Functional Test cases for Zip/Unzip tool?
Given a linked list of integers, write a function to determine whether the given list has a loop or cycle anywhere in the list. The integer values may not be relied upon to be distinct.
You may use the JDK or the standard template library. The solution will be evaluated on correctness, runtime complexity (big-O), and adherence to coding best practices. A complete answer will include the following:
Document your assumptions
Explain your approach and how you intend to solve the problem
Provide code comments where applicable
Explain the big-O run time complexity of your solution. Justify your answer.
Identify any additional data structures you used and justify why you used them.
Only provide your best answer to each part of the question.
Use one of the following skeletons for your solutions.
Java:
public class ListLoopQuestion {
public static class ListNode {
public int value;
public ListNode next;
}
public static boolean hasLoops( ListNode myList ) {
}
}
C++:
struct ListNode {
int value;
ListNode * next;
}
bool hasLoops( ListNode * myList ) {
}
Given a list of test results (each with a test date, Student ID, and the student’s Score), return the Final Score for each student. A student’s Final Score is calculated as the average of his/her 5 highest test scores. You can assume each student has at least 5 test scores.
You may use the JDK or the standard template library. The solution will be evaluated on correctness, runtime complexity (big-O), and adherence to coding best practices. A complete answer will include the following:
Document your assumptions
Explain your approach and how you intend to solve the problem
Provide code comments where applicable
Explain the big-O run time complexity of your solution. Justify your answer.
Identify any additional data structures you used and justify why you used them.
class TestResult{
int studentId;
Date testDate;
int testScore;
}
public Map<Integer, Double> getFinalScores(List<TestResult> resultList){
return null;
}
Given two sorted singly linked lists, implement a function to merge the two lists into a single sorted list and return its head. You may destroy the original lists if you want.
You may use the JDK or the standard template library. The solution will be evaluated on correctness, runtime complexity (big-O), and adherence to coding best practices. A complete answer will include the following:
Document your assumptions
Explain your approach and how you intend to solve the problem
Provide code comments where applicable
Explain the big-O run time complexity of your solution. Justify your answer.
Identify any additional data structures you used and justify why you used them.
Only provide your best answer to each part of the question.
Example:
Input:
List 1: 1->2->3->4
List 2: 1->3->5->7
Output:
1->1->2->3->3->4->5->7
Use one of the following skeletons for your solutions.
Java:
public class Node {
public int value;
public Node next;
public Node() {
value = 0;
next = null;
}
public Node(int value, Node next) {
this.value = value;
this.next = next;
}
}
public class MergeListProblem {
public static Node mergeLists(Node head1, Node head2) {
// your code goes here
}
}
C++:
class Node {
public:
int value;
Node* next;
Node() {
value = 0;
next = NULL;
}
Node(int v, Node* n) {
value = v;
next = n;
}
};
Node* mergeLists(Node* head1, Node* head2) {
// your code goes here
}
what is time complexity of concatenating two int in java example :-
int a=18965;
int b=78521369741;
after concatenation i want ans in primitive integer data types like,
int c=1896578521369741;
i want to know what is the fastest way to do this and what will be the time complexity ?
You're given a machine (Let's say a sprinkler). The machine is controlled with a software component that has UI. The user can set different parameters in the UI. for example : 'speed' : 120 'pressure' : 30
Change the system so it will accept an arithmetical expression in the UI. The expression can contain constants, parameters (e.g 'speed') and operators.
You need to develop the game Snake. What data structures will you use? Code your solution.
Provide a system design for real world URL shortener (solution must scale to millions of users). Back up your assumptions with real numbers.
Given a sorted array of integers, write a function that will return the number with the biggest number of repetitions.
(Asked to refine the solution to be more efficient)
Given a board made of 2 x n squares, and boards made of 2 x 1 squares, write a function that will calculate the number of possible ways to arrange the 2 x 1 boards on the 2 x n board, in a way that will fill it completely.
(Asked to refine the solution to be more efficient)
As a member of the cab finder app team, you are tasked with implementing a CabFinder class that has the following minimal public interface:
class CabFinder implements CabStatusListener {
/**
* Initiates CabFinder. Called only once per app startup.
* @app An application object providing services implemented by
* the rest of the application.
* @maxCabs Nearest number of cabs that can be returned to the user
*/
public void initialize(CabApp app, int maxCabs) {
//Insert code here...
}
/**
* Gets nearest cabs within 1km of the current user’s location.
* These must be the *nearest possible* @maxCabs in the 1km area.
* @return An unordered list of the nearest cabs.
*/
public Cab[] getNearestCabs() {
//Insert code here...
}
/**
* Asynchronous Callback per CabStatusListener (see below). Called when the position of a cab has changed.
*/
void onCabPositionChanged(Cab cab) {
//Insert code here…
}
/**
* Asynchronous Callback per CabStatusListener (see below). Called when a cab’s availability changes.
* @cab The cab whose availability has changed
* @isAvailable true if the cab is now available, false otherwise
*/
void onCabAvailabilityChanged (Cab cab, boolean isAvailable) {
//Insert code here…
}
}
Supporting Classes:
Here are the classes and utilities that are available for your use (you are not required to write any implementation for these classes)
/**
* Coordinates on a 2D map with a one meter granularity.
*/
class Position {
public int x;
public int y;
}
interface Cab {
/**
* Unique identifier of a cab.
*/
int getID();
/**
* Gets the current position of the cab
*/
Position getCabPosition();
/**
* Returns whether or not the cab is available
*/
boolean isAvailable();
}
/**
* Provides services implemented by the rest of the Cab Application.
*/
interface CabApp {
/**
* Gets the current location of the user
*/
Position getUserPosition();
/**
* Returns an iterator that gives access to the list of all cabs in the city
*/
Iterator<Cab> getCabs();
/**
* Registers a CabStatusListener object for change notifications of cab object data.
*/
void register(CabStatusListener listener);
}
/**
* The CabStatusListener interface
*/
interface CabStatusListener {
/**
* Called when the position of a cab has changed.
* @cab The cab object
*/
void onCabPositionChanged(Cab cab);
/**
* Called when a cab’s availability changes.
* @cab The cab object
* @isAvailable true if the cab is available, false otherwise
*
*/
void onCabAvailabilityChanged (Cab cab, boolean isAvailable);
}
how to read a big data file to get the top K values?
Two array with integers.Find the value in both of them with out using set.Find the time complexity?
Three points are given A(x1, y1), B(x2, y2), C(x3, y3). Write a method returning an array of points (x, y) inside the triangle ABC.
A String is given ilke--abdecadc...szx..any thing..like this...element in this given pattern can be any this(like int also and letter till z also)
you have to arrange in pattern--aabbcclike....ie.same charactor together...
Design a Rubik's Cube, including backend database portion.
The way a Knight Given a chessboard, consisting of n×n cells, several of them are cut. Find the path of minimum length for a Knight from one cell to another. The Knight can’t go through cut cells.
Specifications
Input
The first row is set to the number n (2 ≤ n ≤ 50). Each of the next n lines contains n symbols. The symbol # denotes the cut cell, the point - not cut cell, the symbol @ denotes the initial and final cell of the Knight's path (the chessboard contains two such characters).
Output If the path can not be constructed, print "Impossible". Otherwise display the same map as the input, but check all Knight intermediate positions with symbol @. Example
Example input
5
.....
.@@..
.....
.....
.....
5
@..@.
..##.
.....
.....
.....
5
@....
..#..
.#...
.....
....@
Example output
Sample 1
...@.
.@@..
....@
.....
.....
Sample 2
@..@.
..##.
.@..@
..@..
@....
Sample 3
How do you implement a HashTable? What data structures are used internally to implement this HashTable?
Given n. Generate all numbers with number of digits equal to n, such that the digit to the right is greater than the left digit (ai+1 > ai). E.g. if n=3 (123,124,125,……129,234,…..789)
Amazon has many visitors to its site. And it tracks what pages the customers visited, etc and other stuff.
Make an efficient data structure for storing 3 days of information of all those customers who have visited site exactly two different days and searched more than 3 unique pages of the site in those 2 days.
So whoever visited site exactly two days out of these three days and visited more then 3 unique pages should be in the contact list.
What's the efficient approach to solve these kinds of problems??
WAP to check if a binary tree is balanced
which is the bestway to implement stack/queue (would you go for arrays/linkedlist/arraylist etc) explain pros and cons
Write a program to check if a binary tree is balanced
What is the best way to implement Stack/queue... (EX will you use array/linkedlist etc ) explain pros and cons.
Find duplicates in a unsorted array and keep the order of integers as it is.
Look at the following pseudo-code, which computes the n-th Fibonacci number:
int fibonacci(int n)
{
if (n == 0)
{
print(0)
return 0
}
if (n == 1)
{
print(1)
return 1
}
return fibonacci(n - 1) + fibonacci(n - 2)
}
If one calls fibonacci(3), then the following will happen:
* fibonacci(3) calls fibonacci(2) and fibonacci(1) (the first call).
* fibonacci(2) calls fibonacci(1) (the second call) and fibonacci(0).
* The second call of fibonacci(1) prints 1 and returns 1.
* fibonacci(0) prints 0 and returns 0.
* fibonacci(2) gets the results of fibonacci(1) and fibonacci(0) and returns 1.
* The first call of fibonacci(1) prints 1 and returns 1.
* fibonacci(3) gets the results of fibonacci(2) and fibonacci(1) and returns 2.
In total, 1 will be printed twice and 0 will be printed once.
We want to know how many times 0 and 1 will be printed for a given integer N.
INPUT
The first line contains an integer T, denoting the number of test cases.
The next T lines contain an integer N.
OUTPUT
For each test case, print one line of output which contains 2 integers separated by a space. The first integer is the number of times 0 is printed. The second integer is the number of times 1 is printed.
CONSTRAINTS
1 <= T <= 50
0 <= N <= 40
SAMPLE INPUT
2
0
3
SMAPLEOUTPUT
1 0
1 2
The way a Knight Given a chessboard, consisting of n×n cells, several of them are cut. Find the path of minimum length for a Knight from one cell to another. The Knight can’t go through cut cells.
Specifications
Input
The first row is set to the number n (2 ≤ n ≤ 50). Each of the next n lines contains n symbols. The symbol # denotes the cut cell, the point - not cut cell, the symbol @ denotes the initial and final cell of the Knight's path (the chessboard contains two such characters).
Output If the path can not be constructed, print "Impossible". Otherwise display the same map as the input, but check all Knight intermediate positions with symbol @. Example
Example input
5
.....
.@@..
.....
.....
.....
5
@..@.
..##.
.....
.....
.....
5
@....
..#..
.#...
.....
....@
Example output
Sample 1
...@.
.@@..
....@
.....
.....
Sample 2
@..@.
..##.
.@..@
..@..
@....
Sample 3
Impossible
Test the unknown code. You can not see the code, and the only way to test it is through this function: (the 3 arguments are inputs of the unknown code)
void test(string s, int* a, double d){
//black box code
...
...
}
How do you test it to ensure that the code is robust?
This code is written in vb.net language for XO game between two players , TIC TOE
I WANT A LITTLE EXPLANATION FOR EACH MAIN LINE IN THE CODE ..
Here is the cod>>
>
>
Public Class Form1
Dim player1, player2 As String
Dim CurrPlayer As Char
Dim winner As Char
Dim win As Boolean = False
Dim Endgame As Boolean = False
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
CurrPlayer = "O"
player1 = InputBox("First Player Name:")
player2 = InputBox("Second Player Name:")
lblPlayer1.Text = lblPlayer1.Text + player1
lblPlayer2.Text = lblPlayer2.Text + player2
End Sub
Public Function turn() As Char
If CurrPlayer = "X" Then
CurrPlayer = "O"
ElseIf CurrPlayer = "O" Then
CurrPlayer = "X"
End If
Return CurrPlayer
End Function
Public Function CheckWin() As Boolean
If btn1.Text <> "" And btn1.Text = btn2.Text And btn2.Text = btn3.Text Then
winner = CurrPlayer
win = True
ElseIf btn1.Text <> "" And btn1.Text = btn5.Text And btn5.Text = btn9.Text Then
winner = CurrPlayer
win = True
ElseIf btn1.Text <> "" And btn1.Text = btn4.Text And btn4.Text = btn7.Text Then
winner = CurrPlayer
win = True
ElseIf btn2.Text <> "" And btn2.Text = btn5.Text And btn5.Text = btn8.Text Then
winner = CurrPlayer
win = True
ElseIf btn3.Text <> "" And btn3.Text = btn5.Text And btn5.Text = btn7.Text Then
winner = CurrPlayer
win = True
ElseIf btn3.Text <> "" And btn3.Text = btn6.Text And btn6.Text = btn9.Text Then
winner = CurrPlayer
win = True
ElseIf btn4.Text <> "" And btn4.Text = btn5.Text And btn5.Text = btn6.Text Then
winner = CurrPlayer
win = True
ElseIf btn7.Text <> "" And btn7.Text = btn8.Text And btn8.Text = btn9.Text Then
winner = CurrPlayer
win = True
End If
Return win
End Function
Public Sub newGame()
For Each c As Control In Me.Controls
If c.GetType Is GetType(Button) Then
c.Text = ""
End If
Next
CurrPlayer = "O"
win = False
End Sub
Public Sub displayWinner()
If CheckWin() Then
If CurrPlayer = "X" Then
MessageBox.Show("Congratulations, the winner is " + player1, "Congratulations", MessageBoxButtons.OK, MessageBoxIcon.Information)
newGame()
Else
MessageBox.Show("Congratulations, the winner is " + player2, "Congratulations", MessageBoxButtons.OK, MessageBoxIcon.Information)
newGame()
End If
End If
End Sub
Public Sub CheckEven()
Dim empty As Boolean = False
For Each c As Control In Me.Controls
If c.GetType Is GetType(Button) Then
If c.Text = "" Then
empty = True
End If
End If
Next
If empty <> True Then
MessageBox.Show("Players are Even", "Neutral Game", MessageBoxButtons.OK, MessageBoxIcon.Information)
newGame()
End If
End Sub
Private Sub btn1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn1.Click
If btn1.Text = "" Then
btn1.Text = turn()
displayWinner()
CheckEven()
End If
End Sub
Private Sub btn2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn2.Click
If btn2.Text = "" Then
btn2.Text = turn()
displayWinner()
CheckEven()
End If
End Sub
Private Sub btn3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn3.Click
If btn3.Text = "" Then
btn3.Text = turn()
displayWinner()
CheckEven()
End If
End Sub
Private Sub btn4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn4.Click
If btn4.Text = "" Then
btn4.Text = turn()
displayWinner()
CheckEven()
End If
End Sub
Private Sub btn5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn5.Click
If btn5.Text = "" Then
btn5.Text = turn()
displayWinner()
CheckEven()
End If
End Sub
Private Sub btn6_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn6.Click
If btn6.Text = "" Then
btn6.Text = turn()
displayWinner()
End If
End Sub
Private Sub btn7_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn7.Click
If btn7.Text = "" Then
btn7.Text = turn()
displayWinner()
CheckEven()
End If
End Sub
Private Sub btn8_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn8.Click
If btn8.Text = "" Then
btn8.Text = turn()
displayWinner()
CheckEven()
End If
End Sub
Private Sub btn9_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn9.Click
If btn9.Text = "" Then
btn9.Text = turn()
displayWinner()
CheckEven()
End If
End Sub
End Class
Implement data structure for garbage collector in java
Given an array of N integers a1, a2, ..., an, find out what number comes before - positive or negative. If positive, then calculate the sum of the negative elements, otherwise display the greatest positive value.(only Console Application)
(please write with c# console application).Given array .Counting the same number of the last number .
Example .
If input (1 2 3 4 2 2 3 2),i want to count 2 because 2 is the last number of this array.
Result is( 2 is 3 time )because i don't need to count the last number.
what is the best,worst and average case complexity for fibonacci no.s ..explain?
given array .Counting the same number of the last number .
Example .(Write with C#)
If input (1 2 3 4 2 2 3 2),i want to count 2 because 2 is the last number of this array.
Result is( 2 is 3 time )because i don't necessary to count the last number , i need to count only the same number of the last number.
given array .Counting the same number of the last number .
Example .
If input (1 2 3 4 2 2 3 2),i want to output (count 2) because 2 is the last number of this array.
Result is( 2 is 3 time )because i don't necessary to count the last number.
given array . find the same number of the last number .
Example .
If input (1 2 3 4 2 2 3 2),i want to output (count 2) because 2 is the last number of this array.
Result is( 2 is 3 time )because i don't necessary to count the last number.
The value of the variable is entered from the keyboard a. determine the first negative member of the sequence X 1 = a. Xn = tg (Xn-1).(in c #)
Given m numbers in array. Determine how many of them other than the last day of the month.( in c#)
Example-
if input(1 2 2 2 1 3 2)
output is (count the same number of the last number but not necessary to count so,(2 is 3 time )
Given an array of n integers.The value of the array elements are injected with the keyboard .Determine its largest element,the position of this item and move it to the end of the array.
Given an array of N elements (N <= 100). Move it cyclically on M elements right.
You can swap only two consecutive elements. You have to show all steps to convert a string into another string (both strings will be anagrams of each other). E.g. GUM to MUG
GUM
GMU
MGU
MUG
Count Scorecards
In a tournament, N players play against each other exactly once. Each game results in exactly one player winning. There are no ties. You have been given a scorecard containing the scores of each player at the end of the tournament. The score of a player is the total number of games the player won in the tournament. However, the scores of some players might have been erased from the scorecard. How many possible scorecards are consistent with the input scorecard?
Input Format
The first line contains the number of cases T. T cases follow. Each case contains the number N on the first line followed by N numbers on the second line. The ith number denotes s_i, the score of the ith player. If the score of the ith player has been erased, it is represented by -1.
Output Format
Output T lines, containing the answer for each case. Output each result modulo 1000000007.
Constraints:
1 <= T <= 20
1 <= N <= 40
-1 <= s_i < N
Sample Input:
5
3
-1 -1 2
3
-1 -1 -1
4
0 1 2 3
2
1 1
4
-1 -1 -1 2
Sample Output:
2
7
1
0
12
Explanation:
For the first case, there are 2 scorecards possible: {0,1,2} or {1,0,2}.
For the second case, the valid scorecards are {1,1,1}, {0,1,2}, {0,2,1}, {1,0,2}, {1,2,0}, {2,0,1}, {2,1,0}.
For the third case, the only valid scorecard is {0,1,2,3}.
For the fourth case, there is no valid scorecard. It is not possible for both players to have score 1.
For the fifth case, 6-variations of {{3,1,0}[2]}, 3 variations each of {{2,2,0}[2]} and {{2,1,1}[2]}
Max Score: 89pts dynamic
Suggest Edits
For a table created using the following commands. State the SQL SELECT command to find the 1st and 2nd highest salary earned by staff working in DEL or MUM
CREATE TABLE Employees (
ID int NOT NULL AUTO_INCREMENT,
Name varchar(100),
Sal decimal (10,2),
City char (3),
PRIMARY KEY (ID)
);
INSERT INTO Employees (Name, Sal, City) VALUES ('Ramesh',20000, 'BLR');
INSERT INTO Employees (Name, Sal, City) VALUES ('Sunil',24000, 'DEL');
INSERT INTO Employees (Name, Sal, City) VALUES ('Sreeja',21000, 'MUM');
INSERT INTO Employees (Name, Sal, City) VALUES ('Pavan',23000, 'DEL');
INSERT INTO Employees (Name, Sal, City) VALUES ('Maya',24000, 'MUM');
The below Java program prints the numbers from 1 to 50. But for multiples of three print "DNA" instead of the number and for the multiples of five print "RNA". For numbers which are multiples of both three and five print "ATGC". Please identify the three bugs in the code and suggest how they can be resolved.
public class SeqTest {
public static void main(String args[]) {
for(int i = 1; i <= 50; i++) {
if(i % 3 == 0) System.out.println("DNA");
else if(i % 5 == 0) System.out.println("RNA");
else if(i % (3+5) == 0) System.out.println("ATGC");
else System.out.println(“1 to 50”);
}
}
}
Implement the function accumulate below in the language of your choice. The code is in PHP but the syntax of this question should translate into any language. You should have enough information from the comments to define this function correctly. You do not need to implement the function calc.
/**
* This interface should be implemented to represent doing a binary operation on two integers
*/
interface iBinaryOperator
{
/**
* This will take int $x and int $y and return an integer value or throw an exception
*
* @param int $x
* @param int $y
* @return int the value of the binary operation of $x and $y
* @throws MathException
*/
public function calc($x, $y);
}
/**
* This function should go through the array of operands and run calc on each operand IN ORDER, then
* return the accumulated value.
*
* For example the code below would echo the value 10:
*
* $op = new Addition(); //class Addition obviously implements iBinaryOperator
* $operands = array(5,2,3);
* echo accumulate($op, $operands);
*
* This function should work for ANY size array of operands, and ANY class that implements iBinaryOperator
*
* @param iBinaryOperator $op
* @param array $operands array of integers of size N, can be empty
* @return int|string returns an int on successful accumulation, or the string 'error' in error conditions
*/
function accumulate(iBinaryOperator $op, array $operands)
{//Add code here in the language of your choice}
There is a function that scans an array of characters for the character 'e' and prints out each index. What is the complexity? Please implement this function in C, C++, PHP or JavaScript.
If I sort the array, what is the complexity of the sort? What type of sort?
After sorting, what is the complexity if I rescan the array for the character 'e'?
Remove duplicates from a string inplace. The algorithm should be as efficient as possible.
I gave two approaches. First, the simple comparison O(n2) and second, sorting O(nlgon). But the interviewer did not seem satisfied.
Can someone please suggest a better algorithm?
Write a function that could evaluate the algebraic expressions.
a = "2+5/2"
print eval(a) // prints 4.5Write a program to return list of words (from the given list of words) that can be formed from the list of given characters. This is like Scribble game. Say for example the given characters are ('a' , 'c' , 't' } and list the words are {'cat', 'act', 'ac', 'stop' , 'cac'}. The program should return only the words that can be formed from given letters. Here the output should be {'cat', 'act', 'ac'}.
reverse a single linked link - recursive and iterative. tell the O(n) for each.
Q: Pretend I'm a Dog breeder and you are an SDE. Design a solution for tracking my dog's pedigrees.
Followup - pedigree may also be hybrid. need a data structure which can lookup by pedigree to see if dog exists. also should be able to search by pedigree and some characters of dog.
Implement a circular queue of integers of user-specified size using a simple array. Provide routines to initialize(), enqueue() and dequeue() the queue. Make it thread safe.
Write a function that receives three integer inputs for the lengths of the sides of a triangle and returns one of four values to determine the triangle type (1=scalene, 2=isosceles, 3=equilateral, 4=error). Generate test cases for the function assuming another developer coded the function
Given a unsorted array. Create a balanced B tree. Whether it is possible to solve this problem algorithm in logarithmic complexity ?.
Given a unsorted array. Create a balanced BTREE. Whether it is possible to solve this problem algorithm in logarithmic complexity ?.
Given two sorted array in ascending order with same length N, calculate the first K min a[i]+b[j]. time complexty O(N).
some misunderstood first K, to put it straight, to find the Kth min, not the first min
Given a huge N*N matrix, we need to query the GCD of numbers in any given submatrix range(x1,y1,x2,y2). Design a way to preprocess the matrix to accelerate the query speed. extra space should be less than O(N^2) and the preprocess time complexity should be as litte as possible.
A soda water machine,press button A can generate 300-310ml, button B can generate 400-420ml and button C can generate 500-515ml, then given a number range [min, max], tell if all the numers of water in the range can be generated.
Given an input file, find the line with the most vowels ( Easy)
Followup:
Given an input file and any criteria write a function that will find the best score line and return it.
(He told me the best score can be anything, min/max/(anything that can be measured) of the criteria).
Find the K closest points to the origin in 2D plane, given an array containing N points. You can assume K is much smaller than N and N is very large.
You have two numbers decomposed in binary representation, write a function that sums them and returns the result.
Input: 100011, 100100
Output: 1000111
How many steps are there if we start counting from 0 to 10.??? it would be 10 or 11... elaborate plz.
given a N x N matrix find the no. of times a word is present in that matrix. constraints you can move in 3 directions from one cell 1. forward (x+1,y), 2. down (x, y+1) 3. diagonal(x+1,y+1) . Find all the occurance of all the word
solution approach --> BFS or DFS
eg:-
forward means right (x+1,y)
down mean (x,y+1)
diagonal means (x+1,y+1)
it can be done with BFS. {search the no. of occurance of a given word example "sachin" in the whole NxN matrix}
w | s | r | t | g | g|
a | a | c | h | i | n |
k | c | h | u | j | j |
o | h | i | n | y | q |
in this sachin can be found out 3 times.
design a data structure to store time series and implement add operation
Using the following function signature, write a C# function that prints out every combination of indices using Console.WriteLine() whose values add up to a specified sum, n. Values of 0 should be ignored.
public void PrintSumCombinations(List<int> numbers, int n);
• It’s okay to use additional private functions to implement the public function
• Be sure to print out the indices of numbers and not the values at those indices
• Don’t worry too much about memory or CPU optimization; focus on correctness
To help clarify the problem, calling the function with the following input:
List<int> numbers = new List<int> { 1, 1, 2, 2, 4 };
PrintSumCombinations(numbers, 4);
Should result in the following console output (the ordering of the different lines isn’t important and may vary by implementation):
0 1 2 (i.e. numbers[0] + numbers[1] + numbers[2] = 1 + 1 + 2 = 4)
0 1 3
2 3
4
Given a number of arrays where:-
Arr-1={1,2,3,4,5,6,7,8,9 ... N}
Arr-2 is formed by eliminating all the elements that satisfy x*2 from Arr-1 (x belongs to natural numbers) ie.
Arr-2={1,3,5,7,9,11,13,15,17,19 ... }
Similarly Arr3 is formed by eliminating all the elements that satisfy x*3 from Arr2 (x belongs to natural numbers) i.e.
Arr3={1,3,7,9,13,1519,21,25,27 ... }
Arr-k is formed by eliminating x*k elements from Arr-(k-1).
Given number "z" and Array suffix "k" Find if z exists in Arr-k
(with as space and time minimum complexity as possible)
Calculate number of DISTINCT palindromic substrings in a string with help of suffix array or a trie.
Like if aba is string the their are 3 distinct palindromic subsrings:{a,aba,b}
Given a amount and several denominations of coins, find all possible ways that amount can be formed? eg amount = 5, denominations = 1,2,3.
Ans- 5 ways
1) 1,1,1,1,1
2) 1,1,1,2 (combinations aren't counted eg 1,2,1,1 etc)
3) 1,1,3
4) 1,2,2
5) 2,3
Identifying the number of occurrences of each palindrome in a file
We have a fictitious multi-level marketing scheme where a member can recruit one or more other members. At the end of the month, member’s payout is calculated at 10% of his direct sales (items the members sells
themselves) and 4% of sales generated by his recruits and their recruits.
Write a function that calculates the monthly compensation for all members given the original member. You can assume a member can only be recruited by a single existing member.
Given the following interface, please implement the MemberPayoutUtil.calculatePayout function.
public interface Member {
public double getMonthlySales();
private Collection<Member> getRecruitedMembers(); }
public class MemberPayoutUtil {
public static double calculatePayout(Member member) {
// Implement me!
}
}A node which has following fields
a) data
b) next_ptr
c) prev_ptr
can be used to represent doubly linked list, binary tree or none. Given a random pointer recognize whether it forms DLL, Binary Tree or none.
Consider a binary tree for which root node and a target node are given to you. Give the next sibling of the target.(let the target be in level k, then you need to give the immediate node which is in level k)
Given a large file which contains m rows and n columns. Given a column no, sort the column in such a way that corresponding rows also sorted
Given a 2D matrix which contains 0′s and 1′s. Given two points of matrix whose value is 1. Find the path(with only 1′s) between the given points. Can anyone suggest a good algorithm for this ?
given a N x N matrix find the no. of times a word is present in that matrix. constraints you can move in 3 directions from one cell 1. forward , 2. down 3. diagonal . Find all teh occurance of all the word
Write a program to get character count, word count, line count from a file using any programming language?
Printing diagonals of a matrix
How would you structure the game of life (classes, functions etc...)? How would you structure the board if it was played on a sphere?
Find the degree of separation between two people (e.g. LinkedIn's connected feature)
Given an array, divide it into two parts for monte carlo simulations, with 80% of them as training and the rest as testing.
You are given two arrays, how to you find the common elements in them?
My answer: Make a hashmap for one array with the entries as keys and their presence (0 or 1) as values. Then run through the elements of the other array to see which elements match.
Complexity: O(m+n) where m and n are the lengths of each array.
I have a linked list .The first half that is the left side is sorted and the 2nd half -right side is sorted independently.How do I sort them in with out using seperate linked list .I need an efficient solution
Look at the following pseudo-code, which computes the n-th Fibonacci number:
int fibonacci(int n)
{
if (n == 0)
{
print(0)
return 0
}
if (n == 1)
{
print(1)
return 1
}
return fibonacci(n - 1) + fibonacci(n - 2)
}
If one calls fibonacci(3), then the following will happen:
* fibonacci(3) calls fibonacci(2) and fibonacci(1) (the first call).
* fibonacci(2) calls fibonacci(1) (the second call) and fibonacci(0).
* The second call of fibonacci(1) prints 1 and returns 1.
* fibonacci(0) prints 0 and returns 0.
* fibonacci(2) gets the results of fibonacci(1) and fibonacci(0) and returns 1.
* The first call of fibonacci(1) prints 1 and returns 1.
* fibonacci(3) gets the results of fibonacci(2) and fibonacci(1) and returns 2.
In total, 1 will be printed twice and 0 will be printed once.
We want to know how many times 0 and 1 will be printed for a given integer N.
INPUT
The first line contains an integer T, denoting the number of test cases.
The next T lines contain an integer N.
OUTPUT
For each test case, print one line of output which contains 2 integers separated by a space. The first integer is the number of times 0 is printed. The second integer is the number of times 1 is printed.
CONSTRAINTS
1 <= T <= 50
0 <= N <= 40
SAMPLE INPUT
2
0
3
SMAPLEOUTPUT
1 0
1 2
If you look at the following pseudo-code, which computes the n-th Fibonacci number:
int fibonacci(int n)
{
if (n == 0)
{
print(0)
return 0
}
if (n == 1)
{
print(1)
return 1
}
return fibonacci(n - 1) + fibonacci(n - 2)
}
If one calls fibonacci(3), then the following will happen:
* fibonacci(3) calls fibonacci(2) and fibonacci(1) (the first call).
* fibonacci(2) calls fibonacci(1) (the second call) and fibonacci(0).
* The second call of fibonacci(1) prints 1 and returns 1.
* fibonacci(0) prints 0 and returns 0.
* fibonacci(2) gets the results of fibonacci(1) and fibonacci(0) and returns 1.
* The first call of fibonacci(1) prints 1 and returns 1.
* fibonacci(3) gets the results of fibonacci(2) and fibonacci(1) and returns 2.
In total, 1 will be printed twice and 0 will be printed once.
We want to know how many times 0 and 1 will be printed for a given integer N.
INPUT
The first line contains an integer T, denoting the number of test cases.
The next T lines contain an integer N.
OUTPUT
For each test case, print one line of output which contains 2 integers separated by a space. The first integer is the number of times 0 is printed. The second integer is the number of times 1 is printed.
CONSTRAINTS
1 <= T <= 50
0 <= N <= 40
SAMPLE INPUT
2
0
3
SMAPLEOUTPUT
1 0
1 2
Given 78 cents (target) you need to tell how many ways it is possible to make the change using 25 cents(quarter), 10 cents(nickel), 5cents(dime), 1cents(penny)
Given following definition, implement hashmap
Public class HashMap
{
Public void put(object key, object value);
Public void get(object value);
}Given a sorted array with duplicates, move the distinct elements to the top
Ex: 1,1,2,3,4,4,5 -> 1,2,3,4,5
The way a Knight
Given a chessboard, consisting of n×n cells, several of them are cut. Find the path of minimum length for a Knight from one cell to another. The Knight can’t go through cut cells.
Specifications
Input
The first row is set to the number n (2 ≤ n ≤ 50). Each of the next n lines contains n symbols. The symbol # denotes the cut cell, the point - not cut cell, the symbol @ denotes the initial and final cell of the Knight's path (the chessboard contains two such characters).
Output If the path can not be constructed, print "Impossible". Otherwise display the same map as the input, but check all Knight intermediate positions with symbol @.
Example
Example input
5
.....
.@@..
.....
.....
.....
5
@..@.
..##.
.....
.....
.....
5
@....
..#..
.#...
.....
....@
Example output
Sample 1
...@.
.@@..
....@
.....
.....
Sample 2
@..@.
..##.
.@..@
..@..
@....
Sample 3
Impossible
Write a method in Java to:
Find all set of permutations from N number of ArrayLists. Each ArrayList has a different length.
Each permutation is formed by picking one item from each input ArrayList.
You have to exhaust ALL permutations.
Each permutation is a Set, so the order of the items does not matter. For example [a1,b1,c1] is the same permutation as [c1,b1,a1].
Example:
Input: N number of array lists with different length
[a1,a2,a3....]
[b1,b2....]
[c1, c2... ]
...
Output: ALL permutations
[a1, b1, c1...],
[a1,b1,c2..]
....
Note:
The above example is just a sample of potential input to illustrate the output. You have to write code to solve for generalized input.
Reimplement this code so that its results will always be the same, but that it does not cause a stack overflow on large inputs. Your solution must still implement the Folder interface.
Coding
Your class must be named iteration.MyFolder
package iteration;
import java.util.Queue;
public class MyFolder<T, U> implements Folder<T, U>
{
public U fold(U u, Queue<T> ts, Function2<T, U, U> function)
{
if(u == null || ts == null || function == null)
throw new IllegalArgumentException();
if (ts.isEmpty()) {
return u;
}
// The recursive implementation will overflow the stack for
// any data set of real size, your job is to implement a
// non-recursive solution
// return fold(function.apply(ts.poll(), u), ts, function);
return null;
}
}
package iteration;
import java.util.Queue;
public interface Folder<T, U>
{
U fold(U u, Queue<T> list, Function2<T, U, U> function);
}
package iteration;
public interface Function2<T, U, R>
{
R apply(T t, U u);
}I want to calculate number of DISTINCT palindromic substrings in a string.How to do it?
Like if aba is string the their are 3 distinct palindromic subsrings:{a,aba,b}
length of string could be 10^5 range.So i dont think O(n^2) solution will work.So interviewer wanted some better algorithm.
I want to calculate number of DISTINCT palindromic substrings in a string.How to do it?
Like if aba is string the their are 3 distinct palindromic subsrings:{a,aba,b}
length of string could be 10^5 range.So i dont think O(n^2) solution will work.So the interviewer required some better algorithm.But i know only O(n^2) one.
You have n - 1 numbers from 1 to n. Your task is to find the missing number.
I.e.
n = 5
v = [4, 2, 5, 1]
The result is 3.
Given an array with numbers, your task is to find 4 numbers that will satisfy this equation:
A + B + C = D
You have a dictionary which is an array of words and array of strings.
Write two functions
1. Prepare the array of strings to be searched in the dictionary
2. Check if the string contains all valid words or not.
Print an n-ary tree with level. For e.g.
0 foo
1 bar baz
2 foobar barfoo
Desired output:
Level 0: foo
Level 1: bar baz
Level 2: foobar barfoo
class TreeNode
{
String name;
List<TreeNode> getChildren();
}
void printLevels(TreeNode root)
{
// -- CODE--
}The strength of a pair integer sequences is defined by the number of integers that they have in common. You are required to find the strength of several pairs of integer sequences.
INPUT
The first line of input contains T, the number of test cases. T test cases follow. Each test case contains 3 lines. The first line contains two integers N and M, which are the lengths of the two sequences. The next two lines contain the sequences.
OUTPUT
This should contain T lines, each containing an integer representing the strength of the pair of sequences for the corresponding test case.
CONSTRAINTS
The length of each sequence will be between 1 and 20 inclusive
A sequence can contain an integer between 1 and 100 inclusive
Sequences will not contain duplicate integers
SAMPLE INPUT
3
4 4
1 2 3 4
3 4 5 6
4 5
1 2 3 4
1 2 3 5 6
3 4
1 2 3
5 6 7 4
SAMPLE OUTPUT
2
3
0
The binary weight of a positive integer is the number of 1's in its binary representation. For example, the decimal number 1 has a binary weight of 1, and the decimal number 7 (which is 111 in binary) has a binary weight of 3.
Given a positive integer N, find the smallest integer greater than N that has the same binary weight as N.
INPUT
The first line of input contains a number T the number of test cases. The next T lines contain a number N.
OUTPUT
For each test case output a line containing the smallest number greater than N which has the same binary weight as N.
CONSTRAINTS
1 <= N <= 10000
SAMPLE INPUT
2
3
7
SAMPLE OUTPUT
5
11
Given an integer N, find the smallest integer greater than N which is prime.
INPUT
The first line of input contains T, the number of test cases. T test cases follow. Each test case contains a single integer N.
OUTPUT
This should contain T lines, each containing the smallest prime integer greater than N.
CONSTRAINTS
1 <= T <= 5
1 <= N <= 100
SAMPLE INPUT
2
6
11
SAMPLE OUTPUT
7
13
you have the string ={ aabb, aafd,acff,aacg,.....} , if i am writing a as first char or first two char or first three char and so on, it should show the all unique combination of words started with the that characters for eg. say if iam writing aa then it show that aabb or aafd
i have tried using hashmap is it increase my complexity or should i have to use list
Dart thrown land up uniformly and random at a distance from centre of a unit circle. Distance from center is in the range [0,1]. One who lands up farther from the center loses and the loser pays amount equal to distance from the centre. What is the expected pay?
in C++, Suppose we are creating 2 objects like: "sample *s1 = new sample(); and sample *s2 = new sample(); then in this case what will happen if we do like: *s1 = *s2;" Please provide me the answer in detail
In an undirected graph G=(V,E) .Find the number of vertex-disjoint paths between two nodes s and t.
/*
Question 2 / 36 (FizzBuzz)
Write a program which prints the numbers from 1 to N, each on a new line. But for multiples of three print “Fizz” instead of the number 3 and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz”. Read in the input number from STDIN.
Sample Input #00:
15
Sample Output #00 :
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
Explanation:
Position 3,6,9,12 have the word "Fizz" because they are multiples of 3.
Positions 5 and 10 have the word "Buzz" because they are multiples of 5.
Position 15 has the word FizzBuzz because it is a multiple of both 3 and 5.
*/
import java.io.*;
class Solution {
public static void main(String args[] ) throws Exception {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the value of N");
int N=Integer.parseInt(br.readLine());
Solution objSolution=new Solution();
objSolution.fizzBuzz(N);
}
public static void fizzBuzz(int N) throws IOException
{
for(int i=0;i<=N;i++)
{
if((i%5==0)&&(i%3==0))
{
System.out.println("fizzBuzz");
}
else
{
if((i%3)==0)
{
System.out.println("Fizz");
}
if((i%5)==0)
{
System.out.println("Buzz");
}
if((i%3!=0)&&(i%5!=0))
{
System.out.println(i);
}
}
}
}
}
----------------------------------------
What is the complexity of this algorithm ?
Is there any solution with better efficiency ?
Given a binary tree. Modify it in such a way that after modification you can have a preorder traversal of it using only right pointers. During modification you can use right as well as left pointers. Write complete code and dry run it for some test cases
Given N numbers , [N<=10^5] we need to count the total pairs of numbers which have a difference of K. [K>0 and K<10^9]. The solution should have as low of a computational time complexity as possible.
Input Format:
1st line contains N & K (integers).
2nd line contains N numbers of the set. All the N numbers are assured to be distinct.
Output Format:
One integer saying the no of pairs of numbers that have a diff K.
Sample Input #00:
5 2
1 5 3 4 2
Sample Output #00:
3
Explanation:
The possible pairs are (5,3), (4,2) and (3,1).
Find cousins of a given node in a Binary tree and BST.
My Approach:
Steps:(Using level order Traversal)
1. Create a queue q and en-queue root element and take variable qSize and a flag=true
2. Start a loop and check queue is empty or not
{
if qSize==0 then qSize=q.size();
if not flag then print the current queue (q)
Start one more loop and check for qSize>0
{ qSize--
x=deque();
if((x.left != null && x.left== key) || (x.right!= null && x.right== key))
{
flag=false
continue
}
enqueue(x.left)
enqueue(x.right)
}
}For a given string of some sentence, reverse words in that sentence. Ex: I am Don..return Don am I.
For given set of natural number, suppose we can negate some number. Find what all number we should negate such that sum of all number (after negating some number) is zero. For ex: {1,2,3} return {-1, -2}, {1,2,3,4} return {-1,-4} or {-2,-3}. 1st check if such number in given set exist or not. If not return empty array else return numbers.
Picture a restaurant kitchen with tickets of customer’s orders which has a start time, end time of when the order was completed, and price. How would you find the longest contiguous time that tickets were processed within a given day?
using a log generated by a multiprocessor machine, which contains start and end time of each process, find the longest slot of time in which the machine wasn't idle.
the log is sorted by the process's start time
How to convert binary tree to BST inplace.?
P.S. shape of binary tree should be same after converting it into BST
Question: You are given a CSV file with 3 columns -- all integers:
id,parent,weight
10,30,1
30,0,10
20,30,2
50,40,3
40,30,4
0 is the assumed root node with weight 0
which describes a tree-like structure -- each line is a node, 'parent' refers to 'id' of another node.
Print out, for each node, the total weight of a subtree below this node (by convention, the weight of a subtree for node X includes the own weight of X).
You may assume that the input comes pre-parsed as a sequence of Node objects
(substitute the appropriate syntax for java/python/c++):
Node {
int id;
int parent;
int weight;
// ... you can add other fields right here, if necessary
}
implement the following:
public void printSubTreeWeight(List<Node> nodes) {
....}
public static LinkedList reverse(LinkedList current)
{
LinkedList result=null;
if(current==null) return null;
if(current.next==null) return current;
//LinkedList current=head;
LinkedList prev=null;
LinkedList next=current.next;
while(current!=null)
{
next=current.next;
current.next=prev;
prev=current;
current=next;
}
result=prev;
return result;
}
How to add a more memory dynamically to an array without deleting the old memory, means, expanding an aray without deleting the old one?
what is green thread in java..??
Suppose you have N machines connected to a network.
Now you generate a new file on one machine, and want to sync up across all machines. please design a system to accomplish this task and also analyze the error tolerance issue.
Given two unsorted integer arrays A & B of unequal length.
Find an element from A(say 'X') and another element from B(say 'Y') such that |X-Y| is minimum.
Note: A & B can contain positive/negative numbers.
How can you find this without sorting both arrays?
How can you find this by sorting both arrays?
Sorry
Given two log files, each with a billion usernames (each username appended to the log file), find the usernames existing in both documents?
How to partition an array of integers into subarrays so that the average of the two subarrays becomes equal, in efficient way?....
how to convert array into sub arrays
how to convert array into sub array so that we can access element from array into sub arrays in serial manner
Find the longest path in a binary tree
with one bend.
One bend means like SAY I HAVE
1
2 44
3
With one bend means all the nodes means if we start connecting nodes then connect as much as possible in a single line and u can take maximun one bend.Say left left left than right right right.That is maximum one turn..It is not same as diameter say ia have
1
/
2
\
3
Diameter of above is 3 but if we take all the nodes then we will have 2 bends..
So we will two nodes to get nodes with one bend..hope m clear
Implement your own sizeof operator using bitwise operation .
design a system to return an unique ID for each request. For most of requests, the ID value should increase as time goes, the system should handle 1000 requests per second at least.
timestamps alone is not valid since there might be multiple requests with same timestamps.
Given a list of ranges as input ((1,2),(3,4),(3,6),(8,10)),the output would be those ranges that don't overlap.For example, the output could be merging the ranges 1) (1,2),(3,4)
2) (1,2) (3,6) etc
The output cannot contain (3,4),(3,6) as 3 is common to both
You need to find if a number can be expressed as sum of two perfect powers. That is, given x find if there exists non negative integers a, b, m, n such that a^m + b^n = x where 1 <= x <= 1000000 and m > 1, n > 1
Given "n", generate all valid parenthesis strings of length "2n".
Example:
Given n=2
Output:
(())
()()
Write the code in C for the series eg: If a3b2c4 ..is taken then output should be aaabbcccc
explain with example when to use mutex and when to use semaphore
Given a list of unsorted numbers, can you find the numbers that have the smallest absolute difference between them? If there are multiple pairs, find them all.
Sample Input
12
-20 -3916237 -357920 -3620601 7374819 -7330761 30 6246457 -6461594 266854 -520 -470
Sample Output #2
-520 -470 -20 30
Explanation
(-470)-(-520) = 30- (-20) = 50, which is the smallest difference.
Given a list of unsorted numbers, can you find the numbers that have the smallest absolute difference between them? If there are multiple pairs, find them all.
Input Format
There will be two lines of input:
n - the size of the list
ar - the n numbers of the list
Output Format
Output the pairs of numbers with the smallest difference. If there are multiple pairs, output all of them in ascending order, all on the same line (consecutively) with just a single space between each pair of numbers.
Constraints
10 <= n <= 200000
-(107) <= x <= (107), x ∈ ar
Sample Input #1
10
-20 -3916237 -357920 -3620601 7374819 -7330761 30 6246457 -6461594 266854
Sample Output #1
-20 30
Explanation
30- -20 = 50, which is the smallest difference.
Sample Input #2
12
-20 -3916237 -357920 -3620601 7374819 -7330761 30 6246457 -6461594 266854 -520 -470
Sample Output #2
-520 -470 -20 30
Explanation
(-470)-(-520) = 30- (-20) = 50, which is the smallest difference.
Find the maximum-sum subarray of an array.
Write a function to validate the integrity of a binary search tree.
Given the array of digits (0 is also allowed), what is the minimal sum of two integers that are made of the digits contained in the array.
For example, array: 1 2 7 8 9. The min sum (129 + 78) should be 207
Having the following interface
interface CharStream {
boolean hasNext();
char next();
}implement bracket string validation, e.g. "()(([]))" is valid and "(]" is not.
Recursive implementation is required and you have the following signature:
public boolean isValid(CharStream in) {
// your code here
}A subscriber is allowed to make a certain number of telephone calls for a lumpsum charge of Rs.300. Beyond that, he is charged at a certain rate per call. Two subscribers together make 1400 calls, and were charged Rs.425 and Rs.925 respectively. If a single person had made all of the 1400 calls he would have been charged Rs.1550. How many telephone calls are allowed for the first Rs.300?
option
a)300
b) 350
c) 400
d) 450
Everyone knows that finding a loop in the single linked list is using runner and follower method. Could you provide mathematical proof of correctness for it and why it works. I said something like induction hypothesis. Someone help me with the correct answer.
Given N,O where N=No. of digits that can be displayed on calculator and O=No. of multiplication to be performed.
The numbers used for the multiplication can be from {2,3,...8,9}
2<=N<=8
2<=O<=30
write function that will return the largest num that can be obtained after O multiplication.
Eg: N=2, O=3
the function should return 98, since the maximum no. generated after 3 multiplications 2*7*7.
function should return -1 for error or invalid.
Could you replace the CPU cache with an SRAM? If you can what would be an advantage and disadvantage
Application name : Field Survey
It is a web based application where user can create, publish and view online surveys.
Specifications:
Survey Creation: Here user have the facility to create his own survey. He can write multiple questions and each question have multiple check boxes. He can create a Rating on that too.
Brand your Survey: In this section , user can design their survey by providing company name,logo, change the color etc.
Collect response: In this section, user can link the survey to their Facebook,twitter and mails to get response.
Analyze reports: Here they can view survey reports and can able to export it in multiple formats.
Question asked in Neev technologies
Application name : Field Survey
It is a web based application where user can create, publish and view online surveys.
Specifications:
Survey Creation: Here user have the facility to create his own survey. He can write multiple questions and each question have multiple check boxes. He can create a Rating on that too.
Brand your Survey: In this section , user can design their survey by providing company name,logo, change the color etc.
Collect response: In this section, user can link the survey to their Facebook,twitter and mails to get response.
Analyze reports: Here they can view survey reports and can able to export it in multiple formats.
Question asked in Neev technologies
List of parent and child of a binary tree are given in the format (parent, child) –> (p1,c1) (p2,c2) etc [ie, binary tree represented by adjacency list]
How to check "loop" exists in this binary tree or not efficiently.
List of parent and child of a binary tree are given in the format (parent, child) –> (p1,c1) (p2,c2) etc [ie, binary tree represented by adjacency list]
How to check "loop" exists in this binary tree or not in efficiently.
How will you find if a string is a substring of another string in O(n) complexity. For example, "tl" is substring of bottle.
You are given pairs of numbers. In a pair the first number is smaller with respect to the second number. Suppose you have two sets (a, b) and (c, d), the second set can follow the first set if b<c.So you can form a long chain in the similar fashion. Find the longest chain which can be formed
If you have a file that has 1000 unique elements that are unsorted and you have a memory that can accomodate only 200 elements, how will you sort. Hint was to use bitwise operator >
Following code is used by ONE producer and ONE consumer
public void Produce(queue<int> queue, ManualResetEvent mre){
while(true){
lock(queue){
queue.enque(3);
}
mre.set();
}
}
public void Consume(queue<int> queue, ManualResetEvent mre){
while (true){
mre.Reset();
if (queue.Count == 0)
mre.WaitOne();
lock(Queue){
var x = queue.Dequeue();
}
}
}
the last code line causes error, queue is empty-
"var x = queue.Dequeue();"
they asked me to suggest a fix for that.
I have an unordered array of nodes. Each node has an id and parent_id. I want to pretty print out the nodes in an expanded format.
Assumptions:
There is only one root node in the array.
Don't worry about the white space.
Node has a toString() method.
All the ids are arbitrary and unique.
This is a tree and not a graph.
For example:
Sample input:
[{parentId: F, id:G}, {parentId: E, id: F}, {parentId: A, id: B}...]
A (parent_id = null)
B (parent_id = A)
C (parent_id = B)
D (parent_id = C)
H (parent_id = B)
E (parent_id = A)
F (parent_id = E)
G (parent_id = F)Sample output:
ABCDHEFG
Please write a more optimized solution and tell me the complexity.
I have an unordered array of nodes. Each node has an id and parent_id. I want to pretty print out the nodes in an expanded format.
Assumptions:
There is only one root node in the array.
Don't worry about the white space.
Node has a toString() method.
All the ids are arbitrary and unique.
This is a tree and not a graph.
For example:
Sample input:
[{parentId: F, id:G}, {parentId: E, id: F}, {parentId: A, id: B}...]
A (parent_id = null)
B (parent_id = A)
C (parent_id = B)
D (parent_id = C)
H (parent_id = B)
E (parent_id = A)
F (parent_id = E)
G (parent_id = F)
Sample output:
ABCDHEFG
Please tell me the naive solution and its complexity.
Please write a more optimized solution and tell me the complexity.
Suppose we have two functions void g() and void h(). The function h() has been called somewhere in the body of g(). Now using a debugger, we find that that the program crashes as soon as the return statement in h() ( at the end of function h() ) is executed. There is nothing syntactically wrong with the program. How will you debug the code ?
suppose a string is consists of a, b, and c
Now given a integer N, output the amount of all possible strings of length N that don't of have consecutive a,b,c.
e.g. given N=5, string bacca is invalid since the first 3 letters have consecutive a,b,c. and bbbbb is valid.
Is there a way to find nth element in a linked list in O(1) ??
Starting and ending co-ordinates of one-dimensional line segments are given. Find the co-ordinates of longest line segment that can be formed from these segments. Write two functions addSegment() and findMaxSegment(). He asked to write a perfect C code.
Suppose there were n numbers in an array S1, S2, S3, S4.......SN rearrange them in a such a way that they satisfy bellow property.
S1<S2>S3<S4>......
How to represent a number in base -2? (negative -2 base) eg 6 can be 11010 i.e. 16 -8 +0 -2 +0 = 6.
DNA sequence(a string) is given (let say strDNA) and another string to search for(let say strPat). You have to find the minimum length window in strDNA where strPat is subsequence(Write code).
Given number k, for Single linked list, skip k nodes and then reverse k nodes, till the end.
Given an array which has prime numbers, find all duplicates elements of array.
Given a Binary Search Tree, Replace each node with sum of this node and sum of all nodes greater than this node.
Write a function that converts an int into its alpha-numeric equivalent represented as a null terminated string. The function should accept an int as input and return a string as output. For instance, calling the function with an int value of 324 would return a null terminated string containing "324". Ensure that your function checks for appropriate boundary conditions and edge cases. Assume you cannot use any standard libraries (for example, no itoa or sprintf).
Print words of given string in reverse:
"This is test" -> "test is This"
Write code for finding first duplicate element in given array:
[4,3,1,2,5,9,5,4]
output : 5 (not 4)
Lets say there is a device which gets push message for update from server (like android mobile gets) and it switches between wifi and 3G. Write all possible test scenario (negative that might occur in real world, like server gows down etc..)
Lets say there are multiple webservers using single database server on different machine, if someday site response become slow, write all possible test cases that can be written to test/debug this.
Write test scenario for installer of application on windows, which require internet during installation.
Print words of given string in reverse order:
"This is test"
Output: "test is This"
Print array in spiral
123
894
765
Output: 123456789
ABC Inc is a private company focused on oil and exploration. Its net income has been fluctuating since inception. It plans to raise funding for new explorations. The financiers are seeking out if the company had successful runs. If so, which was the most successful one historically. A successful run being a set of consecutive years in which adding the net income year over year results in a value greater than zero. The most successful run would be the one with maximum value. How would you find the most successful run for ABC Inc?
The input would be an array with the net income for all years till date since inception. Output should be a pair of years <Y1 Y2> which represent the most successful run. For simplicity let Y1 and Y2 be array indices. If there wasn't a successful run return -1.
Sample Input1: 3 2 -6 2 1
Output1: 0 1
Sample Input2: -2 -3 -1 0 -6
Output2: -1
Make suitable assumptions and submit your code (programming language of your choice), with relevant comments and test cases.
Write a program to compute the Fibonacci Number for n = 2000
Note: Test it before commenting
Write a function to check if two binary trees have the same structure. This means they look a like or overlap if placed over each other.
There is an array of characters, say A[ ] and there is another array of doubles of equal size say W[ ]. Need to design a method called randomChar( ) that will return a character, but the probability of returning a character at index i ie. A[i] will be W[i].
eg. A = ['a', 'b', 'c']
W = [0.3, 0.5, 0.2]
Then randomChar() called around 100 times should return approx 30 times 'a', 50 times 'b' and 20 times 'c'.
My approach was calculating cumulative probability for the array, eg. W' = [0.3, 0.8, 1.0], then generating random number between 0 and 1 and finally looking up the cumulative array for the right range of the number using binary search. The main problem was the modifications to the normal binary search to check the correct range of generated random number.
We maintain stock prices of various companies. A stream of stock updates are coming in the form of ticker and value pair (example YHOO, 36.00). This value needs to be updated. We have a module of GUI that always displays top 5 stock prices at any given point of time. How would you maintain these values in memory?
My solution was to maintain a max-heap and a map that maps ticker to the corresponding node in the heap. At every update, we look-up the node and update the value, but also note if it is an increase or decrease in value. If increase, we do a sift-up, if decrease, we do a sift-down on the heap for that node. For giving the top five values at any point of time, we don't want to disturb the order in the heap so we would copy the top five levels to a different memory and then perform 5 extract and heapifies on it.
Write an interface for HashMap.
We maintain stock prices of various companies. A stream of stock updates are coming in the form of ticker and value pair (example YHOO, 36.00). This value needs to be updated. We have a module of GUI that always displays top 5 stock prices at any given point of time. How would you maintain these values in memory?
Write a program that takes an arbitrary sentence and abbreviates it by replacing each word with the first letter of the word and the last letter of the word and a number representing the number of characters between the first and last letter. For example, Ford would become F2d. Words are separated by spaces or any other non-alphabetic characters. The program should maintain all non-alphabetic characters in their original form
You are given 2 convex hulls. Develop an algorithm to find all the common points; that is the points that lie in the intersection of these 2 convex hulls. Write code.
how to retrieve particular duplicate element of all rows from a table using linq
Example:
siteId name
2 a
2 b
4 c
4 d
6 e
6 f
i need for each iteration we have to print all rows of particular siteId element.
suppose: for first iteration we have to print rows like:-
2 a
2 b
Using Linq in c#
Suppose you are supplied with a file containing a list of words like ABC, BCD , CAB ( say each word in new line ). now you have to suggest algorithm for this problem -
When a user type some character, we have to suggest him next character and basis of suggestion is that the character you are going to suggest should have maximum occurrence at that position among all these words.
For example , Let's say words are
ABC
BCD
CBA
Now if user types 'A' we have to suggest him 'B' as next character because if you see at second position in all words 'B' is occurring most number of times ( 2 times ).
similarly if he types 'AB' then we need to suggest him third character as 'C' as in third index all words have same occurrence but 'C' comes first.
Q: Design a component that will implement web browser history. the user goes to different site and once he press on history button you should display the last 5 (no duplicates allowed, and 5 can be any N later) if duplicates occur display the most recent one. so if user visit : G,A,B,C,A,Y and than press "history" we will display Y,A,C,B,G. and of course he can go later to two other websites and than press "history" we will show them than the previous 3.
A: I solved it with stack, list and hash table in O(n) but it was too complicated and I didn't like my solution. please suggest something simpler.
There are two methods printA inside Class A and printB inside class B. printA is a static method and printB is a non-static method. Both the methods are synchronized. There exact 100 million threads fired on both printA and printB each. Which method execution will take less time?
public class A {
public static void synchronized printA() {
...////.....
}
}
public class B {
public void synchronized printB() {
...////.....
}
}Design a datastructure for the below functions.
void add(T elem);
void remove(T elem);
T elem removeRandom();
The operation time requirement : O(1)
How to find the number of static objects and dynamic objects created for a class?
Let say,
class MyClass
{
public:
};
int main()
{
MyClass cls;//Static Object
MyClass *obj = new MyClass();//Dynamic Object
...
...
//So on
}
void NewFun()
{
MyClass my;
MyClass *Obj1;
}It should work for all the cases, like big or small projects
Give an matrix of m *n with all the elements=1, Also given is a list of (x,y) points. The question is to zero out all the elements of xth row and yth column.
def mat(alist, xylist):
row = len(alist) #Find num of rows
col = len(alist[0]) #Finf num of columns
for tup in xylist:
x = tup[0]
y = tup[1]
for i in range(row):
alist[i][y] = 0 #Zero out the yth column in each row
for j in range(col):
alist[x][j] = 0 #Zero out the xth row in each column
#Print the final matrix
for list in alist:
print list
def main():
mat([[1,2,3],[4,5,6],[7,8,9], [10,11,12]], [(2,2),(1,1)])
if __name__ == '__main__':
main()
Array Pair Sum. Solve it in O(N) time complexity
how to count the number of prime numbers in a range A B ?
You are given an array A[] of N integers. The array is unsorted, and N integers can take any value from -2,147,483,647 to + 2,147,483,647. You are supposed to find index Q of a pivot point such that, for 0 <= i <= Q, A[i] <= A[Q], and for Q <= j < N, A[Q] <= A[j].
If no such pivot point exists, you should return -1.
The expected worst case time complexity is O(N), and expected worst case space complexity (in addition to array A) is O(N).
Write code for computing binomial coefficient. E.g. "n choose k". Additional constraints are if "n choose k" is greater than 1 billion (1000000000), return -1, else return the answer. E.g. "40 choose 20" is > 1 billion, so you should return -1.
Worse case expected time complexity is O(n * min(k, n-k)), and they had given worst case space complexity too, but I don't remember it.
c program to print input 11000011 and output will be 0000
Ex: 00011000
output =11
C program to print from 1 paragraph it should print from 1st word 1st letter,2nd word 2nd letter, 3rd word 3rd letter if the word is less than 3 letter it should print new line, and again 4th word 4th letter.....
example:
Once when a Lion was asleep, a little Mouse began running up and down upon him.
output will be:
O h
o
e
l e
You are given an array A[] of N integers. The array is unsorted, and N integers can take any values from -(2^31) to +(2^31).
You are required to find index Q of a pivot point, such that for 0 <= i <= Q, A[i] <= A[Q], and for Q <= j < N, A[Q] <= A[j].
The expected time complexity is O(N), and expected additional space requirement complexity is O(N).
Whats wrong in this code?
#include<stdio.h>
#include<stdlib.h>
void mystrcpy( char *string2 ,char *string1 )
{
string2 = malloc(20);
while( *string1 != '\0')
{
*string2++= *string1++;
}
}
int main()
{
printf("****************program starts*************************");
char *str1 ="hello world";
char *str2 =NULL;
mystrcpy( str2,str1);
printf("string1 = %s string2 =%s ",str1,str2) ;
getche();
return 0;
}
why str2 will print NULL here
given a dictionary of wrods,find the pair of word with following property:
1,the two word don't have same letter.
2,the multiple of the two word's length is maximum.
i give a simple O(n*n*k)(k is the average length of word) method.but i think there will be better one .
Given two aligned sequences `a` and `b`. Write a function "findCommon", that finds the longest substring of the longer sequence that align to the smaller sequence in such a way that the alignment length (matching length) can be maximized. Sequences initially were of different lengths but the smaller one is padded with hyphen ('-') after alignment to make it equal to the longer sequence. The length of longer sequence is known in advance (m, which is same for the smaller padded sequence). The output is always the subsequence of the longer string.
The total number of such operations to be done is in billions.
findCommon(a, b, m)
Example 1:
a = ------bixg--
b = xxxxxxbi-gzz
m = 12
output: big
Example 2:
a = xxxxxxbxigxx
b = ------b-ig--
m = 12
output = bxig
Example 3:
a = bigxxxxxxxxx
b = bi-x--------
m = 12
output = bigx
Design a OO system for furniture where there are wooden chairs and tables, metal chairs and tables. There are stress and fire tests for each products.
Find the first non-repeating character in a stream of characters?
Suppose you have all the info of all the restaurants on the world.
1) How would you store all the information ?
2) Get the top 10 recommendation near me. ( using your current position)
explain design and algorithm complexity analysis
Imagine you have the information of all the people from the beginning of the world. How would you know who is the first common ancestor of 2 people.
Let say, You have a reference to yourself and I give you a reference to Albert Einstein, I want to know who is your common ancestor
How would you return/get/print/know the longest Unique word from a text (book, newspaper, lot of data) efficiently ?
In other words, find the word that only occurs 1 time from a big text.
quicksort using divide and counquer . Need code please java
Given a large string T (up to 10M characters) and a large input stream of strings S(up to 1M strings), find for each Si in S if it is a subsequence of T.
String Si is a subsequence of T iff some letters from T can be omitted to obtain Si.
Example:
T - abbebcd
Si - bbcd
return true
T - abbeced
Si - bbbced
return false
Arrange the numbers in an array in alternating order.
For example if the array is [a1, a2, a3, a4.. ]arrange the array such that b1<=b2>=b3<=b4 and so on.
Sampe Input: 3 5 7 8 4 9
Sample Output: 3 < 5 > 4 < 8 >7 < 9
How will you test Amazon.com website?
Implement Hashtable in Java
Explain Mergesort and Hashtable
What is the difference between an array and linked list?
Write code to remove alternate duplicate characters (case insensitive) from a string in place. For eg. "Today is the day" -> "Today ishe ". Also give test cases.
Write code for removing alternate duplicate characters (case insensitive) in a string in place. Also give test cases.
how would you omplement an async task when it's not native in the programming language you're using?
Given an array of pairs of the form <a, b>. We have to find a sub-array such that the 1st element in the pairs are in increasing order and the sum of 2nd element of the pairs in the sub-array is maximum possible
Given N strings, find the smallest string in lexicographic order which contains all the given strings as subsequences
You have three covered baskets labelled "Apples", "Oranges" and "Mixed." All of them are labelled incorrectly. Choosing only one fruit from one of the baskets (and not peeking inside), how can you determine how to relabel the baskets?
You have a gold bar with seven segments. For seven days, you must pay an employee with one gold segment each day. Breaking the bar only twice, how can you ensure the employee gets paid appropriately?
Implement HashTable in java , especially hash function that should take care of any type of keys. The key may be integer or String or Object. But based on that the hash function should find index in the hashArray
Implement Array Class in java.
Using a Java data structure, eliminate all unnecessary/stop words from a string. Assume you are given the string
"To be or not to be - that is the question: Whether it is nobler in the mind to suffer, the slings and arrows of outrageous fortune. Or to take up arms against a sea of troubles, and by opposing end them"
The unnecessary words to remove are "a", "be", "to", "the", "that", "this", "or"
So the resulting string should be like this
"not - is question: Whether it is nobler in mind suffer…
Given two parameters (a target string and a source string), write code that returns the number of times characters found in the source string occur in the target string.
For example, if target="Hello world" and source="llld" then return 4
What are some ways to crack a cryptohash? Is your method efficient, or are there better ways?
What language are you most comfortable with? (I answered C/C++)
What's an unordered map, and how is it implemented?
Design a controller for kids.
(This is a PM interview question, so you're supposed to clarify a lot to clear ambiguity before you get to an answer)
Given an int, write code to return the number of bits that are 1 in O(m) time, where m is the number of bits that are 1.
Create the mirror image of a binary tree.
For a given US based phone number, write a function to return all possible alphanumberic words that can be formed with that number, based on the keypad of a standard phone.
For example, one possible value for 1-800-623-6537 could be 1-800-MCDNLDS
Given a number N, write a program that returns all possible combinations of numbers that add up to N, as lists. (Exclude the N+0=N)
For example, if N=4 return {{1,1,1,1},{1,1,2},{2,2},{1,3}}
How would you create a stack backtrace once an exception has occurred on an x86 platform?
EDIT: Sorry, I should have mentioned that you don't have GDB or any debugging tools. You're supposed to implement everything from scratch in assembly.
Implement a synchronized queue for multiple threads, avoiding race conditions and deadlocks
EDIT: There was a tougher follow up btw: If you use any synchronization mechanisms, how might they be implemented at the assembly level?
In 1-9 keypad one key is not working. If some one enters a password then not working key will not be entered. You have given expected password and entered password. Check that entered password is valid or not
Ex: entered 164, expected 18684 (you need to take care as when u enter 18684 and 164 only both will be taken as 164 input)
Given a string, and the letters are NOT DISTINCT, print out all possible permutations. The solution must be optimized so don't implement the naive O(n!) solution.
Write a function called FooBar that takes input integer n and prints all the numbers from 1 upto n in a new line. If the number is divisible by 3 then print "Foo", if the number is divisible by 5 then print "Bar" and if the number is divisible by both 3 and 5, print "FooBar". Otherwise just print the number.
for example FooBar(15) should print as follows:
1
2
Foo
4
Bar
Foo
7
8
Foo
Bar
11
Foo
13
14
FooBar
I know, easy right? ;)
You have three jars filled with candies. One jar is filled with banana candies, one jar is filled with lemon candies and one jar has a mix of both. All the jars are mislabelled (i.e. all the jars have wrong labels about what kind of candies they contain).
All the candies look very similar in shape, size and color and they even smell the same. The only way to distinguish them is by tasting.
You have to eat one and only one candy to determine the correct jar labels. You can eat that one candy from any jar you want as long as you eat only one in total.
How do you protect your object of your class being deleted by the clients?
please tell me about a good website data structure in c++???
when we have to override equals and hashcode in java..?
what will happened if you dont override .. Explain with program.
Suppose I have some (lng, lat) coordinate. I also have a big list of ranges,
[ { northeast: {lng, lat}, southwest: {lng, lat} } ... ]
How can I most efficiently determine which bucket the (lng, lat) point goes into?
Also, on a design perspective. Would it make more sense for the "list of ranges" to be on some database like mysql, monodb, or on something like memcached, redis?
why strings are immutable ?
how many objects will be created in
String temp = "A" + "B" + "C" ;
explain your answer in detail.
Given s string, Find max size of a sub-string, in which no duplicate chars present.
Find a sub-sequence in a list of numbers where sum of sub sequence is maximum. Numbers can be positive or negative
Find all the anagrams in a mail content.
Given an integer array. Perform circular right shift by n.
Give the best solution.
C={1,2,2,3,4,5}
Sum=5
subset;
{1,2,2}
{1,4}
{2,3}
using exhaustive force in java
ideas
You are given a List containing all the Symbols of the periodic table.
You are also given a List containing all the words in the English dictionary.
How do you find the longest word that can be made using symbols of the periodic table?
Note: Symbols can be 1 or 2 chars long (for eg. O => oxygen, Fe => Iron)
You are given two string named str1 and str2. Your task is to find the minimum window in str1 which contains all characters from string str2.
Given two strings remove duplicates and test it
Given a function to reverse a linked list write code to test the function
Remove common characters from two strings and print the common characters and test cases
Delete m nodes for every n nodes in linked list and write the test cases
Write a 10 digit number in such a way that the 1st digit will describes the no. of occurrence of 1, 2nd digit , no. of occurrence of 2 and so on 9th digit, the no. of occurrence of 9 in the 10 digit number.
Given two (dictionary) words as Strings, determine if they are isomorphic. Two words are called isomorphic
if the letters in one word can be remapped to get the second word. Remapping a letter means replacing all
occurrences of it with another letter while the ordering of the letters remains unchanged. No two letters
may map to the same letter, but a letter may map to itself.
Example:
given "foo", "app"; returns true
we can map 'f' -> 'a' and 'o' -> 'p'
given "bar", "foo"; returns false
we can't map both 'a' and 'r' to 'o'
given "turtle", "tletur"; returns true
we can map 't' -> 't', 'u' -> 'l', 'r' -> 'e', 'l' -> 'u', 'e' -'r'
given "ab", "ca"; returns true
we can map 'a' -> 'c', 'b'
Suppose you have to maintain the stock values of various companies during various periods and return minimum stock value of a particular company over a given period of time.what data structure is best for this.
You have a String which has the value of the text of a magazin or a newspaper.
Find the 10 most used words.
Write a method that takes a string, in this format "aabbaadddc". Encode the string by counting the consecutive letters. Ex: "a2b2a2d3c1"
Explain Binary Search Tree. What is its time complexity?
What is a hash table? Explain how they work (hash function and buckets).
consider 3 entity and show-
1.they are association,table representation,class interpretation using java
Complexity of a function:
int func_fibonacci ( int n) {
if (n < 2) {
return n;
} else {
return ( func_fibonacci(n-1) + func_fibonacci(n-2));
}
}
There is a matrix of very large dimension (10^30 * 10*40) of characters. You need to search a string of length 10^10 inside the matrix. Adjacent characters in any direction can be chosen and same cell can be counted multiple times to find the pattern
You need to select an ad among large no. of advertisements depending on n keywords. What data structure should be used to serve the request efficiently
You visited a list of places recently, but you do not remember the
order in which you visited them. You have with you the airplane
tickets that you used for travelling. Each ticket contains just the
start location and the end location. Can you reconstruct your journey?
Campus Interview question:
Q: What is the difference between a HashMap and HashTable?
A: HashTable is always synchronized - undesirable - HashMap is better
Q: How is ConcurrentHashMap different from Collections.tosynchronized(map)?
A: First locks individual rows the second locks whole structure
Campus Interview question:
Design the File System for an OS.
Campus Interview question:
Search for an element in a rotated sorted array for eg. sorted: {1, 2, 3, 4, 5, 6} rotated: {5, 6, 1, 2, 3, 4}
Campus Interview question:
Find the top k items out of an array where items can have values [0... 100]
Write a function for retrieving the total number of substring palindromes.
For example the input is 'abba' then the possible palindromes= a, b, b, a, bb, abba
So the result is 6.
Updated at 11/11/2013:
After the interview I got know that the O(n^3) solution is not enough to go to the next round. It would have been better to know before starting implementing the solution unnecessarily ...
Construct BST for a given inorder and preorder traversal using ITERATIVE METHOD ONLY
Modify the linkedListType class you already studied by adding the following member functions to it (so here you are a class developer):
void removeTwoByTwoegg; // this function removes the first two nodes and the last two nodes from the linked list. Be warned that the list has to have AT LEAST 4 nodes in order for this function to execute.
void duplicateEachNode(); // this function duplicates each node on the linked list
#include <iostream>
using namespace std;
struct nodeType
{
int info;
nodeType *next;
};
class linkedListType
{
public:
linkedListType();
int listSize();
bool isEmpty();
int seqSearch(int);
void remove(int);
void insertFirst(int);
void insertEnd(int);
void insertAt(int, int);
void removeAt(int);
void print();
void clearList();
void insertOrdered(int);
void removeFirst();
void removeLast();
void removeLast2();
int removeOddSumEven();
~linkedListType();
private:
nodeType *first, *last;
int length;
};
// This function assumes that the list is NOT empty
// and first and last elements are NOT odd
int linkedListType::removeOddSumEven()
{
int sum = first->info;
nodeType *current = first->next;
nodeType *trailCurrent = first;
while(current != NULL)
{
if(current->info % 2 == 0)
{
sum += current->info;
trailCurrent = current;
current = current->next;
}
else
{
trailCurrent->next = current->next;
delete current;
length--;
current = trailCurrent->next;
}
}
return sum;
}
void linkedListType::removeLast()
{
if(length == 0)
cout<<"ERROR: EMPTY LIST" << endl;
else if(length == 1)
{
delete first;
last = first = NULL;
length--;
}
else
{
nodeType *current = first->next;
nodeType *trailCurrent = first;
while(current != last)
{
trailCurrent = current;
current = current->next;
}
delete current;
trailCurrent->next = NULL;
last = trailCurrent;
length--;
}
}
void linkedListType::removeLast2()
{
if(length == 0)
cout<<"ERROR: EMPTY LIST" << endl;
else if(length == 1)
{
delete first;
last = first = NULL;
length--;
}
else
{
nodeType *current = first;
while(current->next != last)
current = current->next;
delete last;
current->next = NULL;
last = current;
length--;
}
}
void linkedListType::removeFirst()
{
if(length == 0)
cout<<"ERROR: EMPTY LIST" << endl;
else if(length == 1)
{
delete first;
last = first = NULL;
length--;
}
else
{
nodeType *current = first;
first = first->next;
delete current;
length--;
}
}
linkedListType::linkedListType()
{
first = last = NULL;
length = 0;
}
int linkedListType::listSize()
{
return length;
}
bool linkedListType::isEmpty()
{
return (length == 0);
}
int linkedListType::seqSearch(int item)
{
nodeType *current = first;
int loc = 0;
while(current != NULL)
{
if(current->info == item)
return loc;
current = current->next;
loc++;
}
return -1;
}
void linkedListType::remove(int item)
{
if(isEmpty())
{
cout<<"Can not remove from empty list\n";
return;
}
nodeType *current, *trailCurrent;
if(first->info == item)//delete the first element, special case
{
current = first;
first = first->next;
delete current;
length--;
if(length == 0)
last = NULL;
}
else
{
current = first->next;
trailCurrent = first;
while(current != NULL)
{
if(current->info == item)
break;
trailCurrent = current;
current = current->next;
}
if(current == NULL)
cout<<"The item is not there\n";
else
{
trailCurrent->next = current->next;
if(last == current) //delete the last item
last = trailCurrent;
delete current;
length--;
}
}
}
void linkedListType::insertFirst(int item)
{
nodeType *newNode = new nodeType;
newNode->info = item;
if(length == 0){
first = last = newNode;
newNode->next = NULL;
}
else{
newNode->next = first;
first = newNode;
}
length++;
}
void linkedListType::insertEnd(int item)
{
nodeType *newNode = new nodeType;
newNode->info = item;
if(length == 0){
first = last = newNode;
newNode->next = NULL;
}
else{
last->next = newNode;
newNode->next = NULL;
last = newNode;
}
length++;
}
void linkedListType::insertAt(int loc, int item)
{
if(loc < 0 || loc > length)
cout<< "ERROR: Out of range" << endl;
else
{
nodeType *newNode = new nodeType;
newNode->info = item;
if (loc == 0) //insert at the begining
insertFirst(item);
else if (loc == length) //insert at the end;
insertEnd(item);
else
{
nodeType *current = first;
for(int i = 1; i < loc; i++)
current = current->next;
newNode->next = current->next;
current->next = newNode;
length++;
}
}
}
void linkedListType::removeAt(int loc)
{
if(loc < 0 || loc >= length)
cout<< "ERROR: Out of range" << endl;
else
{
nodeType *current, *trailCurrent;
if(loc == 0) //remove the first item
{
current = first;
first = first->next;
delete current;
length--;
if(length == 0)
last = NULL;
}
else
{
current = first->next;
trailCurrent = first;
for(int i = 1; i < loc; i++)
{
trailCurrent = current;
current = current->next;
}
trailCurrent->next = current->next;
if(last == current) //delete the last item
last = trailCurrent;
delete current;
length--;
}
}
}
void linkedListType::print()
{
nodeType *current = first;
while(current != NULL)
{
cout<<current->info <<endl;
current= current->next;
}
}
void linkedListType::clearList()
{
nodeType *current;
while(first != NULL)
{
current = first;
first = first->next;
delete current;
}
last = NULL;
length = 0;
}
void linkedListType::insertOrdered(int item)
{
nodeType *newNode = new nodeType;
newNode->info = item;
if(first == NULL)
{
first = last = newNode;
newNode->next = NULL;
length++;
}
else if(first->info >= item)
{
newNode->next = first;
first = newNode;
length++;
}
else
{
nodeType *current = first->next;
nodeType *trailCurrent = first;
while(current != NULL)
{
if(current->info >= item)
break;
current = current->next;
trailCurrent = trailCurrent->next;
}
if(current == NULL) //insert at the end
{
last->next = newNode;
newNode->next = NULL;
last = newNode;
length++;
}
else
{
trailCurrent->next = newNode;
newNode->next = current;
length++;
}
}
}
linkedListType::~linkedListType()
{
clearList();
}
int main()
{
linkedListType l1;
l1.insertAt(0, 10);
l1.insertAt(1, 1);
l1.insertAt(2, 3);
l1.insertAt(3, 40);
l1.print();
return 0;
}
Given two Btrees. these trees "may" have right and left branches swapped. Now compare it
Find number of palindromes in a string
Given a set of n points (coordinate in 2d plane) within a rectangular space, find out a line (ax+by=c), from which the sum of the perpendicular distances of all the points will be minimum. This can has a general usecase like, in a village there are few house, you have to lay a road, such that sum of all the approach roads from each house will be minimum.
Given a matrix M with (with positive or negative numbers) find the largest sum S of any sub-matrix of M.
Find the length of the longest palindrome in a string
in this i have to improve the enqueue function
enqueue returns the queue after adding the element but the original queue is not to be changed
and same is for dequeue function
import java.util.ArrayList;
import java.util.List;
import java.util.NoSuchElementException;
public class PersistentQueue<E>{
private List<E> queue;
public PersistantQueue<E>(){
queue=new ArrayList<E>();
}
private PersistentQueue(List<E> queue){
this.queue=queue;
}
public PersistantQueue<E> enqueue(E e){
/*
Returns the queue that adds an item into tail of this queue without modifying this queue ( how to return without cloning ??)
*/
if(e==null){
throw new IllegalArgumentException();
}
List<E> clone = new ArrayList<E>(queue);
clone.add(e);
return new PersistantQueue<E>(clone);
}
public PersistantQueue<E> dequeue(){
/*
Returns the queue that removes the object at the head of this queue without modifying this queue ( here also how to do instead of clone as it it slow ??)
*/
if(queue.isEmpty()){
throw new NoSuchElementException();
}
List<E> clone = new ArrayList<E>(queue);
clone.remove(0);
return new PersistantQueue<E>(clone);
}
public E peek(){
if(queue.isEmpty()){
throw new NoSuchElementException();
}
return queue.get(0);
}
public int size(){
return queue.size();
}
}
Implement below function.
int getRandom(int N, int K[])
Constraints:
->K is sorted and contains elements in range [0,N)
->Output should be a random number between [0,N) excuding elements from K
->probability of generated number should be 1/(N-K.length) and not 1/N
-->int uniform(int N) is given which returns random number [0,N) with 1/N probability for each number.
->No more than O(1) memory
->No more than O(N) time
Below is my solution but it uses O(N) space.
public int randomNumber(int N, int[] K) { // K is sorted
//assumed size of K is less than N
int remains[] = new int[N-K.length];
//i is index [0,N-1], j is an index of K, k is an index of remainings
//Fill remaining array
for (int i=0,j=0,k=0;i<N;i++){
if (i!=K[j]){
remainings[k++]=i;
}else{
j++;
}
}
int index = uniform(remainings.length);
return remainings[index];
}
Time complexity: O(N)
Space Complexity: O(N)Solve the given equation in one variable 'x'. The equation will be either linear of quadratic, i.e. the maximum degree of the equation will be 2. The usual precedence of the operation will hold true. There won't be any other operations apart from +, -, * and /. x will not present in the donominator, and only the elipse-shaped "()" brackets can exist in a given test. The constant in the equation will be smaller than 1000. We can not ignore the * operation.
Sample Input
1> x + 3 * 5 = 80
2> (x-3)*(x+4) = 0
3> x * (2 * x - 3) + x / 3 = x / 3 - 1
Output
1> 65
2> -4 and 3
3> 0.5 and 1.0
Given a result in string of pass, fail, blocked, unknown as pppppppfffffbbbbbuuuuu or pppppppppppppppfffffff or pfpfpfpfpfpfpfpfpuuuuuuuuu or any combination of characters from p,f,b, or unknown character say u or x or y or z... question is write a program which can identity a pattern like all tests passed or all tests are failing or tests started failing (blocking issue may be) or unknown pattern... this is what my friend recall if someone also faced this question and recall better explaination , please add.. interviewer asked to code the solution not algo...
Tossing a coin ten times resulted in 8 heads and 2 tails. How would you analyze whether a coin is fair? What is the p-value?
In addition, more coins are added to this experiment. Now you have 10 coins. You toss each coin 10 times (100 tosses in total) and observe results. Would you modify your approach to the the way you test the fairness of coins?
Find numbers which are palindromic in both their decimal and octal representations
From a given input array, for each element, find next higher element present in each array. for example {40,50,11,32,55,68,75} output should be {50,55,32,55,68,75,-1} for element if no higher element is present, print -1. complexity should be less than O(n^2) . you can use datastructure and no constraint on space complexity.
Sort two string arrays and merge into one in alphabet order? which sorting algorithm would be good here?
suppose str[]="ab" and str2[]="badg" and str3 should be aabbdg, should work for all combinations.
algorithm to reverse a singly linked list using one pointer without any additional datastructures
Websites like Pandora recommend music based on user preferences. What kind of information would you need in such a design?
Given an integer, print out all the prime numbers smaller than that integer.
We 1 bottle poison among 4 bottle,but we don't know in which bottle poison are kept.after eating poison bottle person die in 1 hour.how many minimum person are required for finding poison bottle....MY ANS- 2 Explaination-1,2,3,4 1st person will eat 1 bottle in first minutes and after 29 min.it means excatly in 30 min he will take 2nd bottle.if he will die in 6o min .means poison are in 1st bottle or person will die in 90 min means poison in 2nd bottle.simillarly 2nd person will do.....AM I CORRECT....PLZ COMMENT.
Given N,O where N=No. of digits that can be displayed on calculator and O=No. of numbers which are to be multiplied.
The numbers used for the multiplication can be from {2,3,...8,9}
2<=N<=8
2<=O<=30
Write function that will return the largest number that can be obtained after multiplying O numbers.
Eg: N=2, O=3
The function should return 98, since the maximum no. generated after multiplying 3 numbers is 2*7*7. Function should return -1 for error or invalid.
The function returns whether it is possible to form the number num by multiplying mult numbers
Design remote controller for me.
Given a string, write a function to determine if the string is a palindrome ignoring spaces. Your code should run optimally in a memory-constrained environment.
eg "ABBA" = true
" ABB A" = true
"ABXA" = false
" ABBXBAB" = false
You have 10 million IP addresses. (IPv4 4 byte addresses). Create a hash function for these IP addresses.
Hint: Using the IP's themselves as a key is a bad idea because there will be a lot of wasted space.
Given an array, remove the duplicates and return a unique array keeping the first occurrence of the duplicates and the order.
[@2, @1, @3, @1, @2] --> [@2, @1, @3]
The input to the program would be a number D and a string STR.
Dissimilarity Example1:
Set S = (pot, pat)
Dissimilarity = 1
Explanation:
First character 'p' and last character ‘t’ matches but 'o' and 'a' do no match. So dissimilarity = 1
Objective is to find a number N which is equal to the number of sets, where a single set S will contain two equal length substrings of STR whose dissimilarity less than or equal to D.
Dissimilarity for each set S is measured by the number of index positions where characters of both strings do not match. write a programm in c#
if Akatsuki message is like:
XWV
UTS
RQP
You should read it as
PQR
STU
VWX
Write a programm in c#
Design a function to gives real time statistics of your web traffic,count one day's website visit ,count one week's website visit
Given two sorted arrays, we can get a set of sums(add one element from the first array and one from the second). Find the Nth element in the set of sums. Suppose that array A is {1,3,4,8,10}, array B is {20, 22, 30, 40}. then the sum set will be{21(1+20),23(1+22 or 3+20), 25(3+22), 24(4+22)...} the 3rd element in the sum set is 25.
difference between thread and process.
design an alarm clock for a deaf person.
3 fruit baskets having apple, orange and mix. all labeled wrong. with only one sample taking from one basket but not peeking find out which basket has which one.
9 identical balls. one ball is heavy. find the heavy ball with only 2 measurements ........ dead easy.
Given: left bottom and right top coordinates of a rectangle.
n numbers of rectangle ceated holes.Find the area of holes.
eg.one rectangle in in top ,second intersect with the first at right and simillarly third at left and forth at bottom.It creates a hole in between.Find the area of the hole.
solve (x-1)(x-9)=8;
there are N number of matchboxes numbered 1...N.each matchbox contain various number of stick.Two player can alternatevely pick some amount of stick from the higest stick containing box . The player is condidered win if there is no stick after his move.Find the final move so that the move player win.
Note:In case the number of stick is equal ,pick the stick from the higest numbered box.
eg: 3 box contain stick as:1,1,1.
if u take 1 stick from 3rd numbred box you will any how win the match.
Question was on Arithmetic progression
Example :
Given the AP :- 1 3 7 9 11 13 find the missing value "which would be 5 here".
Conditions :
Get an user for the length of AP sequence and make sure user provides length is above 3.
Get the input in a single line ex:- "1 3 5 7 9 11"
Provide the solution in O(n) or less if you can.
given a file with each line containing information <country name,state name,city name,no_of_people visited> the user want to know the no of hits of the site from the no of people visited but the request may change frequently e.g sometime it may be asked 2 find hits according to cities,sometime it may be according 2 state,might be according 2 country or around the world.design the algorithm clearly mentioning the data structure 2 b used in the algorithm
Check if a given tree is a valid BST
Engineers at Google have decided to call any integer (+ve, -ve or 0) that is divisible by at least one of the single digit primes (2, 3, 5, 7) as Walprimes. Thus -21, -30, 0, 5, 14 etc are Walprimes, while -121, 1, 143 etc. are not Walprimes.
Now, consider a n-digit integer d1d2d3..dn. Between any 2 consecutive digits you can place either a (+) sign, a (-) sign or nothing. So, there are 3n-1 different expressions that can be formed from it. Some of the expressions so formed may evaluate to a Walprime. For example, consider the 6 digit integer 123456: 1 + 234 - 5 + 6 = 236, which is a Walprime, but 123 + 4 - 56 = 71, which is not a Walprime.
Your task is to write a program to find the no. of expressions (out of the possible 3n-1 expressions) that evaluate to a Walprime, for a given input. Note that leading zeroes are valid. For example, if the input is 1202004, it can be split as 12 + 020 - 04 etc. Also, the input itself can contain leading zeroes.
Input format: (Read from stdin)
The first line of input contains a single integer 'T' denoting the no. of test cases.
Each of the following 'T' lines contain a single string 's' (of length 'n') denoting an input for which you need to find the no. of valid expressions evaluating to a Walprime.
Output format: (Write to stdout)
Output exactly 'T' integers (one per line), where the ith line denotes the no. of valid expressions that evaluate to a Walprime for the ith input string. Since the output can be large, print all the quantities modulo 1000000007.
Sample testcase:
Input:
2
011
12345
Output:
6
64
Explanation:
For the first test case, s = "011". There are 32 = 9 valid expressions that can be formed from this string, namely {0+11, 0-11, 0+1+1, 0+1-1, 0-1+1, 0-1-1, 01+1, 01-1, 011} . Out of these 9 expressions, only the following 6 of them evaluate to a Walprime: {0+1+1, 0+1-1, 0-1+1, 0-1-1, 01+1, 01-1}.
Constraints:
There are 3 data sets.
For the first data set (5 points) -
1
For the second data set (10 points) -
1
For the third data set (15 points) -
1
Why do you think the company has been named so?
Q1. What Data structure would you use if you have to store millions of numbers.
WAP a program to find a contineous subset whose sum is divisible by 7. We are given a array of number (negative+positive).
calculate the complexity of your algorithm
Given a catalog of books, with the following attributes
Name
Author
Publisher
Publisher Year
Price
Inventory count
Implement functionality for
1. get / search all books (by author/by name/by publisher) Also need to support partial string search
2. Update catalog (book)
Features:
* Explain why you use a particular data structure.
* Free to choose any language, C/C++/C#/Java/Perl/Python.
* Need to design the classes appropriately, that can allow scalability, encapsulation.
* Need to allow search similar to that currently provided by Flipkart.
Code in around 1 hour.
Write a code to read and write a matrix in below given way.
Note : no. indicates the sequence here.
I/P
1 2 3
4 5 6
7 8 9
O/P
1 6 7
2 5 8
3 4 9
Given a binary tree, find out the maximum sum of value from root to each leaf.
find_Max(Node *root){
if (root==null)
return 0;
else
return max((find_Max(root->left), find_Max(root->right))+root->value;
}Find the largest k numbers in an enormous array of numbers. You cannot sort the array. Give the run time of the algorithm.
Write code to read comma-delimited data from a file and display the contents to the screen. The contents need to be sorted in descending order of the second element of each line.
Here is some sample data to illustrate how it is formatted:
ADGB, 35, helloWorld
GHFR, 23, niceWeather
GFTD, 40, superMan
OPUK, 35, angryBirds
Write a method in Java to reverse an array in chunks of 3. You should also consider cases where an array is not a multiple of 3.
For example:
Input array: {1,9,6,4,5,8,3,1,5}
Expected results:{6,9,1,8,5,4,5,1,3}
how do we compare two objects in java.
An array of integer represents a bar graph, where index of array is X axis (width = 1) and Y axis represents height of the bar graph at X, find out how much water will retain if it rains infinite on the structure. Only portion of graph that retains water is enclosed area due to height difference of bar graph. You need to assume that each bar itself doesn't store any water.
e.g. {1,2,3} then no water is stored
{6,4,1} then no water is stored
{3,2,1, 5} then 3 unit water is stored between 3 & 5 (1 unit on 2 and 2 unit on 1)
Given a dictionary of words, return words that can be formed by using only symbols from Chemistry Periodic Table.
e.g. ARK (Ar-K)
SICK (Si-C-K) etc.
(All the time while writing the code, I was just thinking about Br-Ba :) )
Given a binary representation of an integer say 15 as 1111, find the maximum longest continous sequence of 0s. The twist is it needs to be done in log N. I could think of O(N) solution. but couldn't go for log(N).
For example. 10000101
the answer should be 4, because there are 4 continouos zeroes.
For a given map (ie Bing map) given longitude/latitude/ how would you design the system so that when map longitudeDelta/latitdueDelta changed you add additional pins on map for regions that was not previously cover.
In another word, how would you design it to avoid getting and displaying duplicated pins
4 individual numbers which could be permuted in 4 factorial ways. permutation of these 4 integers is an 0indexedarray consisting of 4 digits in some order when integers are different. the best permute of the 4 integers is by the following funciton func(summ) = abs(summ[0] - summ[1]) + abs(summ[1] - summ[2] + abs(summ[2] - summ[3])) that would give maximum value.
method signature
public int answer(int w, int x, int y, int z){
}
w = 5
x = 3
y = -1
z = 5
the sample permute wiht given numbers in the given function that would give maximum value is as follows.
for the
summ[0] = 5
summ[1] = -1
summ[2] = 5
summ[3] = 3
This should be done in O(1)time ans space complexity. My questions wordings may be confusing, but the function and sample data are perfectly correct.
Give N=no. of players
K=No. of fans
likeMatrix=It is a sting array of size K where each element of array have size N.
(contains 0 and 1 only) where if a[i][j] ==1 represents fan(i) likes player(j)
Ex. N=5
K=3
like={ "10101","00001","01011","...","...." }
Count min. no. of players required to put in team such that each fan likes atleast one player.
You have two integer arrays. Treat these arrays as if they were big numbers, with one digit in each slot. Perform addition on these two arrays and store the results in a new array.
If you are behind the schedule on a project, what will you do?
I was asked by multiple interviewers.
WAP to sort prime numbers smaller than given N by digits. If N is 40, the output should be 11, 13, 17, 19, 2, 23, 29, 3, 31, 37, 39, 5, 7.
Follow-up question: limit memory usage.
You will get a continuos stream of numbers.... u have to add these numbers to some list (u shouldn't sort it)... and any time user does a pop on the list, we should return the minimum of the list and remove it from the list... the minimum should now point to the next minimum in the list.
In a language, there are only 4 characters ‘h’, ‘i’,’r’, ‘e’. and we have to write a function which takes a string as input and returns whether the given input string is a “valid word” or not.
Definition of valid word :
1. A given word is a valid word if it is of the form h^n i^n r^n e^n where n >=1. (eg: hhiirree)
2. Valid words has concatenation property i.e. if w1 and w2 are valid words w1w2 is also a valid word.
There is a sentence that your friend knows, but while giving it to you, he lost all the spaces. You have a dictionary with you, that will tell you given word exist or not. How would you reconstruct the original sentence using it.
Question on function hiding using inheritance.
Write a method to check if the given tree is binary search tree.
Replace element of an Array with nearest bigger number at right side of the Array in O(n)
For example if the input Array is
7, 5, 6, 3, 4, 1, 2, 9, 11
output array should be
9, 6, 9, 4, 9, 2, 9, 11, 11
You visit yelp.com (or any other website).
What happens? Describe as much of the web stack as you possibly can. (This question is meant to last 45 mins).
Suppose the sub-requests can be queued at each server, and the servers are running all the time. Discuss feasible on-line algorithms that can achieve sub-optimal solutions with N ~ 10000.
A service system has n DIFFERENT servers; each one provides one unique service to the clients. Clients submit requests to the service system, each request may have multiple sub-requests; each sub-request is to a DIFFERENT server. A request can have at most n sub-requests. Each sub-request takes 1 time unit to finish at any server. The finish time of a request is the finish time of its LAST finished sub-request. The notation "total request finish time" is the sum of all requests' finish time.
1. Design an off-line algorithm to reorder the execution order of sub-requests on the servers, so that "total request finish time" can be minimized (if multiple solutions exist, only one solution is enough). Discuss the complexity of the algorithm.
Input format:
Line 1: number of requests.
Line 2: number of servers in the system, n.
Line 3 to (n+2): sub-requests (denoted with their parent requests’ IDs) at each server, the i’th line represents the sub-requests to be served at server ID = (i-2).
Output format:
Line 1 to (n-1): the execution order of sub-requests, so that “total request finish time” can be minimized.
Sample input 1:
4
4
1 2 3 4
3 2 1 4
4 2 1 3
2 3 4 1
Sample output 1:
1 2 3 4
1 2 3 4
1 2 3 4
1 2 3 4
(The “total request finish time” of input is 14; and output is 10).
Sample Input 2:
6
6
1 6 2
4 3 5 1
1 2
1 2 4 6
3
5 6
Sample Output 2:
6 1 2
3 1 4 5
1 2
6 1 4 2
3
6 5
(The “total request finish time” of input is 19; and output is 15).
2. Discuss feasible algorithms that can achieve sub-optimal solutions with N ~ 10000.
3. Suppose the sub-requests can be queued at each server, and the servers are running all the time. Discuss feasible on-line algorithms that can achieve sub-optimal solutions with N ~ 10000.
Alyssa P. Hacker is interning at RenBook (人书 / 人書 in Chinese), a burgeoning social network
website. She needs to implement a new friend suggestion feature. For two friends u and v (friendship is undirected), the EdgeRank ER(u; v) can be computed in constant time based on the interest
u shows in v (for example, how frequently u views v’s profile or comments on v’s wall). Assume
that EdgeRank is directional and asymmetric, and that its value falls in the range (0; 1). A user
u is connected to a user v if they are connected through some mutual friends, i.e., u = u0 has a
friend u1, who has a friend u2, . . . , who has a friend uk = v. The integer k is the vagueness of the
connection. Define the strength of such a connection to be
k
S(p) = pie ER(u ; ui):
i=1 i-1
For a given user s, Alyssa wants to have a way to rank potential friend suggestions according to
the strength of the connections s has with them. In addition, the vagueness of those connections
should not be more than k, a value Alyssa will decide later.
Help Alyssa by designing an algorithm that computes the strength of the strongest connection
between a given user s and every other user v to whom s is connected with vagueness at most
k, in O(kE + V ) time (i.e., for every pair of s and v for v 2 V nfsg, compute the strength of the
strongest connection between them with vagueness at most k). Assume that the network has jV j
users and jEj friend pairs. Analyze the running time of your algorithm. For partial credit, give a
slower but correct algorithm. You can describe your algorithm in words, pseudocode or both.
What is the in order successor of 6 in the given BST? (Ah! This is not an assignment. I am a working professional).
4
2 6
1 3 5
4.5 5.5
2 is left child of 4 and 6 is right child of 4.
1 is left child of 2 and 3 is right child of 3.
5 is left child of 6.
4.5 is left child of 5 and 5.5 is right child of 5.
Given a Tree (not essentially a BST). Find the right most cousin of a given node.
There is a matrix which contains white cells , black cells and only one gray cell, need to go from (0,0) to (N-1, N-1) if Arra[N][N]
constraints:
a. The path should cover only white cells and should go via grey cell.
b. The node once visited cannot be visited again.
White cells are represented by 0, black cells by 1 and grey cell by 2.
I am capturing the voice as buffer at client side and sending that buffer to server using Socket programming, then at server side I receive it and play using SourceDataLine , and its properly running on LAN but when I deploy it to Remote Server the voice carry noise data.
tell me the solution.
How many times “Hello World” is printed by following program?
int main()
{
if(fork() && fork())
{
fork();
}
if(fork() || fork())
{
fork();
}
printf(“Hello world”);
return 0;
}
a. 16
b. 20
c. 24
d. 64
Write a function to retrieve the number of a occurrences of a substring(even the reverse of a substring) in a string without using the java substring() method.
Ex: 'dc' in 'abcd' occurs 2 times (dc, cd).
00011111100011
11100010111110
11000111111100
00111100001111
00110000110000
11000100000110
find the maximum areas(m*n) covered by 0.
Find Common Ancestor of given two nodes A and B
Condition :Node does not have the parent pointer and data value.
So its is like class Node {
Node L;
Node R;
}
I mentioned below Solution. Since they didnt give me Parent I created one for each node than did back tracking from two given Nodes A & B;
Node commonAncestor(Node A, Node B, Node root){
HashMap<Node> map=new HashMap<Node>();
Queue q=new Queue();
map.(root,null);
q.enqueue(root);
while(!q.isEmpty()){
Node curr=q.dequeue();
if(curr.L !=null)
map.put(curr.L,cur);
if(curr.R !=null)
map.put(curr.R,cur);
}
Node prev=A;
Node next=null;
while(map.contains(prev)){
next= map.get(prev);
map.remove(prev);
prev=next;
}
prev=B;
next=null;
while(map.contains(prev)){
prev=map.get(prev);
}
}
Given an input list of lists.. flatten the list. For e.g.
{{1,2}, {3}, {4,5}} ... Output should be {1, 2, 3, 4, 5}
Find the max height of a binary tree.
Write your own regular expression parser for following condition:
az*b can match any string that starts with and ends with b and 0 or more Z's between. for e.g. azb, azzzb etc.
a.b can match anything between a and b e.g. ajsdskjb etc.
Your function will have to parameters: Input String and Regex. Return true/false if the input string satisfies the regex condition. Note: The input string can contain multiple regex. For e.g. az*bc.g
Given a array of numbers, for each element give the product of every other number. eg 1 2 4 3--> 24 12 6 8
Find the first repeating character in a given string.
Given two values in a Binary Tree - how do you find the lowest common ancestor?
How to find if a number is power of 4 in O(loglogn).
There is a file of size 100 gb and you have given a memory of size 100GB. How you will sort the file on basis of ASCII. File is having line of text inside it. No line in the file is repeated.
Find if 2 lists of rectangle are exactly equal. How would you sort the lists?
1. Using C or Java programming language, implement merge sort. Run it on the following list of numbers:
56 93 65 34 13 19 88 84 67 48 51 21
Each time your main recursive function is called, output the following information (print each item on one line, and print \****" at the very beginning of the function):
• The input list that the merge sort function is being called on
• The left and right lists it splits into, before recursively calling merge sort
• The left and right lists, after they are recursively sorted
• The result of merging the left and right lists
Submit the printed output from this program, as well as the source code
WAP to generating all the possible combination of a given character.
Example:-
Input: {a,b,c}
output: {a,b,c,ab,ac,ca,ba,,cb,bc,abc,bca,cab,cba,acb,bac}
Give me an algorithm to reverse a string.
How would you test the Location Services feature on a smartphone?
How would you test the Add Friend feature on Facebook?
How do you motivate software engineers? How to you encourage quality? What are your engineering principals?
white a function/method to determine if two strings are anagrams. What is the time complexity of the algorithm (big O)? Is there a more efficient way?
write a function to determine if two strings are anagrams? what is the run-time (big O) of this? Is there a better way to do this?
Given a sorted array where only number occurs once and others occur twice. e.g. arr = { 0, 0, 1, 1, 2, 4, 4, 5, 5}. Find the number occurring once in o(lgn)
Given a sorted array (e.g. arr = { 0, 0, 0, 0, 1, 3, 5 }) which has been rotated clockwise less than arr.length times, return the number of rotated times.
Given a binary tree, an integer k and a node, you have to find all the nodes at distance k from the given node.
write a function to generate a random number in a given range.
Condition:
Each number should be generated exactly n times, i.e., if each number has to be generated only 5 times and
the number 7 has already occured 5 times then your function should not generate 7 again.
Actual he asked question linking with array but it is bit confusion, he asked to do the above only
Q: Given a sorted 2D N x N array (where array[i][j] < array[i][j+1] and array[i][j] < array[i+1][j]), can you write a function that converts this to a sorted 1D array?
The obvious and naive way that I thought of was to convert the entire array into a 1D and do a mergesort on it, but there must be a better way than that. I'm wondering what the better and more efficient way is.
determine the series of numbers entered (array a) from the encoded output of the program (array b).
For i from 0 to size - 1:
For j from 0 to size - 1:
b[(i+j)/32] ^= ((a[i/32] >> (i%32)) & (a[j/32 + size/32] >> (j%32)) & 1) << ((i+j)%32)How to use private members of Base class in Subclasses without exposing them ?
There are n points on a 2D plan, find the k points that are closest to origin ( x=0, y=0)
Hi,
Following was a question that was asked to me in one of the interviews.
We know anagram of eat is: tea and ate
The question is:
We have a program. We feed a list of 10 thousand alphabets to this program.
We run the program.
Now at run-time, we provide a word to this program eg. "eat"
Now the program should return the number of anagrams that exist in the list of 10 thousand alphabets. Hence for an input of "eat", it should return 2.
What will be the strategy to store those 10 thousand alphabets so that finding the number of anagrams becomes easy.
Given a list of arraylists containing elements, write a function that prints out the permutations of of the elements such that, each of the permutation set contains only 1 element from each arraylist and there are no duplicates in the list of permutation sets.
Eg: consider the following lists
L1= {a1,b1,c1,d1}
L2={a2,b2,c2}
L3= {a3, b3, c3}
Valid Permutations are:
{a1,b2,c3}
{a1,a2,a3}
{b1,c2,b3}
...
...
..
Please note that
{a1,b2,c3} is same set as {b2,a1,c3}
You have an array of length n, containing values of length 0 to n-1.
Tell me if there exists a duplicate (return true or false).
Do it in constant space and O(n) time.
Write a program that prints the numbers from 1 to 100. But for multiples of three print "Fizz" instead of the number and for the multiples of five print "Buzz".
For numbers which are multiples of both three and five print "FizzBuzz".
Additionally, instead of printing "Fizz" or "Buzz", create a lookup such that 3 --> "Fizz", 5 --> "Buzz", 7 --> "Woof" and so on. The signature of the method would be:
List<String> fizzbuzz(int start, int end, Map<Integer, String> lookups) { ..}
The expected output is of the format : 15:FizzBuzz, 21:FizzWoof, 105: FizzBuzzWoof, etc
which are wrong statements in this code?
interface TestInterface{
void myMethod();
abstract void myMethod2();
private void myMethod3();
}Asked question on expansion of {2x-3y}^3 ?
and equation of line?
Difference in SOAP and IIOP?
What is externalizable interface?
java code to calculate size of String without using any length or size method?
String input = "abcde ";
int output = 5;
Write code in java to move char to next position with minimum space requirement?
String input = "abcde";
String output = "eabcd";
Do thread join without join function
Given n players with each having a skill level. Divide the players in 2 equal in number(max 1 difference if n is odd) such that the total skill difference between the teams is minimum.
write a program that will analyse the string....
char str[90]="my brother is taller than me@1233334. I always a short man,but smart than him";
1)Remove spaces between words,
2)Find the longest word in the String,
3)Search and count the number of letters"e" in the string 4)Extact the number of integers in string
5)Extract the number of doubles in string
6)Extract the number of words in string
7)Identify the number of sentences in the String.
write a program that will analyse the string....
char str[90]="my brother is taller than me@1233334. I always a short man,but smart than him";
1)Remove spaces between words,
2)Find the longest word in the String,
3)Search and count the number of letters"e" in the string 4)Extact the number of integers in string
5)Extract the number of doubles in string
6)Extract the number of words in string
7)Identify the number of sentences in the String.
You are given a grid of numbers. A snake sequence is made up of adjacent numbers such that for each number, the number on the right or the number below it is +1 or -1 its value. For example,
1 3 2 6 8
-9 7 1 -1 2
1 5 0 1 9
In this grid, (3, 2, 1, 0, 1) is a snake sequence.
Given a grid, find the longest snake sequences and their lengths (so there can be multiple snake sequences with the maximum length).
Given two String, s1 and s2.
to find the longest substring which is prefix of s1, as well as suffix of s2.
if there is one dimensional array of unsigned integer array, how you can remove the all occurrences of that number from the array..? he wants to be with minimum complexcity
swap Two Number by using ternary operator
Here is a good puzzle:
How do you write a program which produces its own source code as output?
Given an array consisting of both positive and negative numbers,
rearrange the elements such that positive and negative numbers are
placed alternatively, constraints are that it should be in-place and
order of elements should not change.
Given an input array. Write an Algorithm to
print all possible combinations in the array that
sum up to given input K.
Eg : If input array is {1,2,3,4,5} and K is 7
then O/P should be
1 6
3 4
2 5
Implement a stack with O(1) push, pop, and min
Implement a LRU cache with O(1) addCache and removeCache.
Given a regular expression with characters a-z, ' * ', ' . '
the task was to find if that string could match another string with characters from: a-z
where ' * ' can delete the character before it, and ' . ' could match whatever character. ' * ' always appear after a a-z character.
Example:
isMatch("a*", "") = true;
isMatch(".", "") = false;
isMatch("ab*", "a") = true;
isMatch("a.", "ab") = true;
isMatch("a", "a") = true;
WAP to print the longest bitonic sequence in an array.
Given numbers from 1 to n , find a and b such that a <= b*10 and b <= a*10. The set should contain numbers which are violating these conditions with each other.
valid Number-- A number is called valid if it satisfies as in following example:
A=1248 then products when taken 1,2,3,and 4 at a time are:
1,2,4,8,2,8,32,8,64,64(1,2,3,4,1*2,2*4,4*8,1*2*4,2*4*8,1*2*4*8)
if all these numbers are unique the number is valid here the number is not valid.
When you were in a conflict with a teammate or team member and he persuaded you to go his way? What would you do?
what will you do when client is asking you to provide something which doesnt make any sense?
Input - List<String> ["star", "rats", "ice", "cie", "arts"]
print all anagrams in buckets:
["star", "rats", "arts"]
["ice", "cie"]
The signature of unimplemented method is given:
public void anagramBuckets(List<String> input);I was given this question during phone interview.
As we know facebook always asks questions from graph theory he asked me this problem to code-
there is a grid of n*n where each cell represent an Island or and some of these are very dangerous so u have to avoid these during path selections.You can move up,down,left ,right.You are given your starting position ,positions of dangerous Islands and position some specific Islands.Your task is to deliver a message to all the specific Islands in minimum number of moves to all specific Islands(NOTE- there are also chances that no moves are possible to cover all specific Island ,in such case you have to tell "NOT POSSIBLE TO DELIVER ALL ",otherwise output minimum moves).
Fibonacci Numbers: A number is said to be Fibonacci number if it follows the fibonacci property. (Ex: 112, 1123, etc). But additionally, it need not necessarily start with 1, as with the normal fibonacci series. So, in this new definition, 112(1,1,2) is a fibonacci number and so is 121224(12,12,24), and so is 252550(25,25,50). So, given any two numbers as input, print out all the Fibonacci Numbers within that range..
Implement simple tail command in C++.
Long Subtraction -- Given two arrays A, B, each contains elements of digits, return an array of A - B. Your machine can only do calculation of less than 20.
eg. A = [1,2,5,7,5];
B = [3,4,8,9];
A - B = [9,0,8,6];
Given a keyboard with every letter maps a digit from 0 to 9, return all possible permutation of given a n digit number.
eg. 0 <- z,a,q,x,s,w
1 <- c,d,e
2 <- v,f,r
3 <- b,g,t
...
Then permutation of num 1230 will be:
cvbz
cvba
cvbq
...
create a java api for mood detection for the image captured from webcam with approximate indexing
String temp = "A" + "B" + "C" ;
how many objects are created
Write code to print all different paths in an undirected graph from a given source to destination with no loop(any node can be at most once in a path ).
"Given an array of strings, find the string which is made up of maximum number of other strings contained in the same array.
e.g. “rat”, ”cat”, “abc”, “xyz”, “abcxyz”, “ratcatabc”, “xyzcatratabc”
Answer: “xyzcatratabc”
“abcxyz” contains 2 other strings,
“ratcatabc” contains 3 other strings,
“xyzcatratabc” contains 4 other strings"
Given a array of characters of this replace the characters which occur continously with the character and no. of times it occured e.g. AAAABCCDDD A4BC3D3 (count for characters that occurs once can be ignored). Do it Inplace.
Implement Cache in Java.
function should support
Object get(key)
void put(key, value)
Spiraly print n*n matrix.
Eg: [1,2,3,4]
[12,13,14,5]
[11,16,15,6]
[10,9,8,7]
Should print
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16
Given a class with n people,where each people plays a game with all other people. Results are with you. You have to arrange them in a queue with a condition that, a[i] should have won a[i-1], for all I, you don’t need to care about a[i-2] . (a[i] may win or lose a[i-2]).
Print all pairs(sets) of prime numbers (p,q) such that p*q <= n, where n is given number
Given a undirected graph, source and destination, write the code to find the total number of distinct nodes visited, considering all possible paths.
An arraylist containing datatype studentsScores are given where studentId, and results are twostates of this datatype. Each student takes more than 10 exams. We need to return the averages score of each student as a Map<student, average score> where the average score is calculated by taking the average of top 5 exams of a student.
First we iterate the arraylist and create another Map<Integer, ArrayList<>> where the inner ArrayList has values of test scores. Iterating the arrayList to find avergae score and adding it to the another Map<student, averageScore>. What is the complexity of this?
Write a program to find the reoccurence the character in a given string ,if it find in that given string , come out from the loop.
For Example
char *str = "abcdefgha";
here a is occured second time, so comes out from the loop.
Given a chess board of finite length (NxN), start position of a knight(x, y) and an end position (p, q). 1) Find number of minimum hops required to reach end position.
2) Check your solution extendable to infinite length chess board ??
Design a DS to perform
1. Insert
2. Search
3. Delete
4. Get Random
All in O(1).
n1 pairs of “{} ” brackets
n2 pairs of “[] ” brackets
n3 pairs of “() ” brackets
Print all valid combinations of all the pairs
A student needs to implement a BST structure to solve a problem, but instead he used a linked list. New value will always be added at beginning of a linked list. So basically at each step after insertion , root of BST and head of link list should point to same node. Then give an example of input sequence, in which his implementation works…
Given an array consisting of both positive and negative numbers, 0 is considered as positive, rearrange the elements such that positive and negative numbers are placed alternatively, constraints are that it should be in-place and order of elements should not change.
write a program takes array input{1,0,2,3} and num =3.and provides output {1,2}{0,3}{2,1}{3,0} sum equals the num.
write test cases for a program which accepts x,y as input and outputs x power of y.
what is the automation scope of the above testing
experience on performance testing.
difference between load and stress testing
what are the parameters that interests you in the above tests
write test cases to test amazon website
what is accessibility testing.how do you test a website,mobile app for accessbility
Complete the below function which takes an arraylist and displays the list in the expected output
public class TreePrinter {
public static void printTree(Iterable<Relation> rs) {
// your code
}
}
public static class Relation {
String parent;
String child;
public Relation(String parent, String child) { ... }
}
}
Example input:
List<Relation> input = newArrayList();
input.add(new Relation(“animal”, “mammal”));
input.add(new Relation(“animal”, “bird”));
input.add(new Relation(“lifeform”, “animal”));
input.add(new Relation(“cat”, “lion”));
input.add(new Relation(“mammal”, “cat”));
input.add(new Relation(“animal”, “fish”));
TreePrinter.printTree(input);
Expected output:
line 1: lifeform
line 2: animal
line 3: mammal
line 4: cat
line 5: lion
line 6: bird
line 7: fish
// merge sorted arrays 'a' and 'b', each with 'length' elements,
// in-place into 'b' to form a sorted result. assume that 'b'
// has 2*length allocated space.
// e.g. a = [1, 3, 5], b = [2, 4, 6] => b = [1, 2, 3, 4, 5, 6]
//how to do it without rearanging the b array
boolean isBST(const Node* node) {
// return true iff the tree with root 'node' is a binary search tree.
// 'node' is guaranteed to be a binary tree.
}
n
/ \
a b
\
c
How would you assign numbers if you were AT&T, describe a data structure
Given an n x n matrix A(i,j) of integers, find maximum value A(c,d) - A(a,b) over all choices of indexes such that both c > a and d > b.
Required complexity: O(n^2)
Implement an algorithm to print all possible valid combinations of braces when n pairs of paranthesis are given.
I tried this code executing. I checked with System.out.println statements too. But I couldn't understand how this prints ( ( ) ). I have two questions.
1) If we give count as 2, this code should generate only ( )( ). But how does it go for another execution of whole addParen to generate (( ))
2) The second if block(that is, if(rightRem > leftRem) within the else block of allParen is always after if(leftRem > 0), then how come this is able to generate
( ( ) )
public static void addParen(ArrayList<String> list, int leftRem, int rightRem, char[] str, int count) {
if (leftRem < 0 || rightRem < leftRem) return; // invalid state
if (leftRem == 0 && rightRem == 0) { /* all out of left and right parentheses */
String s = String.copyValueOf(str);
// System.out.println(str);
list.add(s);
} else {
if (leftRem > 0) { // try a left paren, if there are some available
str[count] = '(';
addParen(list, leftRem - 1, rightRem, str, count + 1);
}
if (rightRem > leftRem) { // try a right paren, if there’s a matching left
str[count] = ')';
// System.out.println(str);
addParen(list, leftRem, rightRem - 1, str, count + 1);
}
}
}
public static ArrayList<String> generateParens(int count) {
char[] str = new char[count*2];
ArrayList<String> list = new ArrayList<String>();
addParen(list, count, count, str, 0);
return list;
}
public static void main(String args[]) {
ArrayList<String> list = generateParens(2);
for (String s : list) {
System.out.println(s);
}
System.out.println(list.size());
}
}
What should be strategy to minimise the impact on external system which is using our table's data for processing?
You are given an array whose each element represents the height of the tower. The width of every tower is 1. It starts raining. How much water is collected between the towers?
Eg. [1,5,3,7,2] – then answer is 2 units between towers 5 and 7.
Can you predict the output of the following code?
for (int i = 0; i < 101; i++) {
if (i % 2 == 0) {
System.err.print(i);
} else
System.out.print(i);
}a word is valid if the letters follow their natural order in it. abcd is valid, acde is valid aaaa is valid, acb is not valid. condition for valid: char1<=char2<=char3<=… given a length n find all valid words of length n.
There are n items and v[i] is the value of i-th item. Now we want to convert value of i-th item to d[i],for each i from 0 to n-1 inclusive.
For this conversion, at each step for particular i, we can decrease value of i-th item by 1 and value of j-th item is increased by 1 for each j not equal to i.
It is possible for some of items to have negative value, but after all transformations all item should have positive value.
Find minimum number of steps required for changing current values to one that is required. If it's impossible, print -1.
Input:
First line contains single integer n - the number of items. Second line contains n integers separated by single space - value of item. Next line contains n integers - value of item required.
Constraints:
1 <= n <= 50
1 <= v[i], d[i] <= 50
Example:
input:
1
1
2
output:
-1
input:
3
3 2 2
4 5 3
output:
5
What is spring Initialization Bean interface?
suppose we have
parent class
add( int , int)
child class
add(double, double )
if we call child_instance.add( int, int), is it correct syntax?
what is generic Eraser in java?
decide collection in java where you can store this range based search?
age range : group id
0-25 : 1
26: 50 : 2
> 51 : 3
best way to store this DS and In search input is age and we should get group id?
when to use serialization vs externalizable interface?
If new object is created by thread then where object's attributes are going to be created? stack or heap?
class Myclass{
String data;
MyObject object;
public void mehtod(){
data = new String("ddd");
object = new MyObject();
int i = 10;
}
Suppose now thread A creates object of this class and calls method() then where data, object and i will be created? heap or stack of thread?
Given that logs are being generated by may web servers, design your logs processor, to optimize for the query "get the count of the logs generated in the last 5 minutes".
You have been given a series of 'n' numbers and the series is in a random order. Write a program to find the median of the series with minimum complexity.
Find the word in the given sentence.
i)Check whether it exists
ii)If exist means return count and index.
Ex:
string="CSK lost to RR"
substr="CSK"
CSK exist in above string.The substr CSK is presented at the index of 0-2 in string.
The count is 1.
Remove the word in a Sentence with the given word
Ex:
i love you
i)remove the word "love" in above
ii)insert the word " hate" in above
op:
i hate you
[do this step by step]
Finding the minimum in a BST.
The known solution is
public Node minimum(){
Node current, last;
current = root;
while(current != null){
last = current;
current = current.left;
}
return last;
}
The above code doesn't find 0.5 as the minimum.
1 and 3 are children of 2, 0.5 is left child of 3 and 3.5 is right child of 3
2
/ \
1 3
/ \
0.5 3.5
You have two arrays of integers, where the integers do not repeat and the two arrays have no common integers.
Let x be any integer in the first array, y any integer in the second. Find min(Abs(x-y)). That is, find the smallest difference between any of the integers in the two arrays.
Assumptions: Assume both arrays are sorted in ascending order.
Check if a binary tree is BST.
I know the solution but I want to know will this code work
public boolean IsBST(Node root){
if(root.left <= root && root.right > root){
IsBST(root.left);
IsBST(root.right);
}else{
return false;
}
return true;
}
Question 1 / 1 (Path Explosion EASY)
You were given a Binary Tree (not necessarily a Binary Search Tree) to play with, say T. T had some special properties
Each internal node in T had exactly 2 children
Each internal node in T was represented by an uppercase English alphabet (A-Z)
Each leaf node in T was represented by a lowercase English alphabet (a-z)
You were told remember T as long as you could. Hence, you memorised the string formed by traversing T in post-order. You used something similar to the pseudocode below
toPostOrderString (node)
if node is leaf
return node.value
else
T = ""
T = T + toPostOrderString(node.left)
T = T + toPostOrderString(node.right)
T = T + node.value
return T
Now, time has come to use that string again. The Eye has contacted you. Yes, the secret organisation mentioned in "Now you see me" ( don't tell anyone they are real !! )
You remember the string you memorised back then. You must reconstruct the binary tree T. You are also given a string A. All the characters of A are uppercase English alphabets. Let us assume that T has L leaves. Then, there will be exactly L paths from the root to the leaves - 1 unique path to each leaf.
You have to tell The Eye the number of paths out of L, on which, A exists as a sub-sequence. Look at the explanation for the Sample Case 1 for clarity.
You have to implement the method explodePaths in the code. explodePaths is passed the following parameters, respectively
N, the number of nodes in T
S, the string representation of the post-order traversal of T. Of course, the length of S will be equal to N.
K, the length of the string A
A, the string you must find in the paths from the root of T, to the leaves in T.
Note
It is not necessary that T is balanced. But, each internal node always has exactly 2 children. It is possible that both those children are internal nodes also. It is possible that only one of those children is an internal node.
For the given string S, because of the constraint that each internal node has exactly 2 children, you will always be able to determine the tree T, uniquely.
It is not necessary that all characters in T are unique. There may be several nodes with the same value.
In this problem statement, by sub-sequence we mean not necessarily contiguous. This is different from a sub-string.
Do not print the answer in explodePaths. Just return the value. The code-template interviewstreet provides does the input and output itself.
Consider the following tree
A
/ \
t B
/ \
/ \
B A
/ \ / \
x y a b
This tree is given in Sample Case 1 as
N = 9
S = "txyBabABA"
K = 2
A = "AA"
Now, there are 5 leaf nodes, and hence, 5 paths from the root to leaves - 1 for each leaf.
- A-t
- A-B-B-x
- A-B-B-y
- A-B-A-a
- A-B-A-b
Out of these 5 paths, you have to find the number of paths, on which "AA" exists as a sub-sequence. Of course, there are only 2 such paths
- A-B-A-a
- A-B-A-b
Hence the expected answer is 2.
In the same T above
The answer for A = "BB", is 2
The answer for A = "BA", is 2
The answer for A = "AB", is 4
The answer for K = 1 and A = "A", is 5
The answer for K = 1 and A = "B", is 4
The Sample Case 2 has a little more complicated T. The string S in Sample Case 2 is yeBgeuCBxAB.
Constraints
N ≤ 10000
K ≤ 100
The expected time complexity of the algorithm is O(N).
Given an integer N, print numbers from 1 to N in lexicographic order.
Details: To be implemented without using character conversion (or Strings).
Example:
N = 25
Print:
1
10
11
..
19
2
20
21
..
25
3
4
5
6
7
8
9
A simple solution using Strings (may not be acceptable):
System.out.print("\n\tLexicographic Order\n\nEnter an integer: ");
Scanner input = new Scanner(System.in);
Integer n = input.nextInt();
List<String> list = new ArrayList<String>();
for (int i = 1;i<n;i++){
list.add(""+i);
}
Collections.sort(list);
for (String j: list){
System.out.println(j);
}arrange books in box, if box carry weight == books
weight then take another box..... find the no of box required.
Given set of N threads generate sum of all numbers in an array of known size M
What is high dynamic range rendering and why is it important for realistic rendering?
Write a function to generate a second array of numbers containing running average of N elements from the original array
So for instance if the original array is,
2,6,4,2,3 and N=3
result = 2,4,3,4,3
you can assume the corner elements can be filled with original elements where there are not enough elements to take avg of N elements
You have written a memory manager and after using it your coworker complains that he is facing severe issues of fragmentation. What could be the reason(s) and how can you fix it
Input - array of integers size N, integer Threshold. Output - the number of pairs (x, y) of distinct elements with condition x + y <= Threshold. Is that possible to implement it with O(n) ?
How do you check if a binary tree is balanced or not? Please traverse through this code and explain how the complexity is O(N).
public boolean isBalanced(Node root){
if(checkHeight(root) == -1){
return false;
}else{
return true;
}
}
private int checkHeight(Node root){
if(root == null){
return 0;
}
int leftHeight = checkHeight(root.left);
if(leftHeight = -1 ){
return -1;
}
int rightHeight = checkheight(root.right);
if(rightHeight = -1){
return -1;
}
int heightDiff = leftHeight - rightHeight;
if(Math.abs(heightDiff) > 1){
return -1;
}else{
return Math.max(leftHeight, rightHeight) + 1;
}
}
Please traverse for the following tree.
A
/ \
B C
/ \ / \
D E F G
\
H
Initially there is a number n written on board. Two players start playing a game turn by turn. Each player has to replace the number n written on the board by n-2^k (for some k >= 0 such that 2^k < n)?
Also the number n-2^k has to be as beautiful as n (The beauty of a number depends on the number of one's in its binary representation). The player loses the game when he can't select any such k.
Given the initial number n, determine which player will win the game if both players play optimally. n > 0 and n <= 10^9.
Two numbers min and max age give. Generate all numbers between them without repeated digits.
Example input:
98 and 103
output:
98,102,103
Debug Scenarios for :
1. Double Clicking the MP3 File and Nothing happens
2. Double clicking the Player and then playing the file and nothing is heard
Test scenarios for a web page having following fields:
Name : First and last
Phone
DOB with date filter
Upload photo
Chose exam center (radio button)
Highest degree (Drop Down)
Submit Button
you are given n-strings 1you have to find whether a chain can be termed with all the strings given number n? A chain can be formed b/w strings if last char of the 1st string matches with 1st char of second string. For example you are given
number of strings = 3
first string=sdfg
second string=dfgs
third string=ghjhk
they can be concatenated as ->
second first third
dfgs sdfg ghjhk (characters at concatenation points are same)
so concatenated string is-dfgsdfghjhk
ArrayList list = new ArrayList();
what would you improve in this code?
Given a string say "ABCD". Now create a new string with duplicates of each character in the original string and append the reverse of the same string (with duplicates) excluding the last character.
First iteration: AABBCCCCBBAA
[ABC three types of chars; Here c is the last char.Ignore duplicates after the last char c]
Second iteration: AABBBBAA
[here b is the last char]
Third iteration: AAAA
[no second char left]
I was asked this ques in my first phone interview.
Replace a string within another string WITHOUT LIBRARY FUNCTIONS.
I/p:
Str="anonymous";
O/p:
str1="anonykggse";
Design an architecture for REST APIs where you have to upload big data like images/videos etc. Request should be async. Follow up: How will you tune the performance if you have millions of requests coming at same time? Clues: Queueing the request, Storing data in filesystems rather than traditional DB etc.
Open Ended: Design an email system
Given two trees, find if tree 2 is the mirror image of tree 1.
Find the latest version of released software. For e.g1. 2 and 2.2.. latest is 2.2.
eg2: 3.1 and 3.1.3... latest version is 3.1.3... version is passed as string in above format.
Design an architecture for REST APIs where you have to upload big data like images/videos etc. Request should be async. Follow up: How will you tune the performance if you have millions of requests coming at same time? Clues: Queueing the request, Storing data in filesystems rather than traditional DB etc.
You are given an array in which you’ve to find a subarray such that the sum of elements in it is equal to zero.
I was asked this question during campus placement drive :
You have a Timer which goes to from a certain range ( n to 0), where n is not fixed and we can have it as much as we want.
The timer when goes to 0 an associated callback for the request is done.
We have multiple requests coming into the system, however the Timer is insufficient to deal with them at all at once ( it can deal with a figure less than number of requests).
How do you reuse the timer and handle all asynchronous requests?
Rotate a M*N matrix by 90 degree.
Is this answer right?
public void rotateMN(int[][] input){
int i = input.length;
int j = input[0].length;
int m = j;
int n = i;
int[][] newArray = new int[m][n];
for(int j = input[0].length-1, m=0; ;i--, m++ ){
for(int i = input.length-1, n=0; i >= 0 ; i--, n++){
newArray[m][n] = input[i][j];
}
}
}
Will this also work for N*N matrix rotation by 90 degrees?
The time complexity is O(N) since it just traverse the input matrix and copy it to the new matrix. The space complexity is (MN) + (MN) = So MN.
Is it possible to do rotation for M * N matrix in space? If so please provide that answer
Whats this space and time complexity?
Perform String replace in given string in C.Dont use library functions..
Write a function to check if the given chemical equation is balanced or not?
Ex:
Cu + S = CuS
2H2 + 02 = 2H2O
Print 010101010.... or 1010101010... without using arithmatic operations.
There are n items and length of each item is b. Different bar codes written on item consist of only 0's and 1's. We need to put items in the bag but with a condition. Most of the bar codes differ only in 1 or 2 bits. So we can only put an item into other bag if it has more than 2 differing bits from all the other items of that bag.
Find no. of bags needed.
INPUT :
First line contains two space separated integers, N and B.
N : no of items to be carried, B : length of each bar code.
Next N lines each contain B space separated integers (0's and 1's only) denoting Bar Code of corresponding items.
OUTPUT :
Minimum no. of bags required.
CONSTRAINTS :
1 <= N <= 10,000
1 <= B <= 32
Example:
INPUT:
5 6
1 1 1 1 1 1
0 0 0 0 1 0
1 1 0 0 0 1
1 1 1 0 0 0
1 0 0 0 0 0
OUTPUT:
2
EXPLANATION :
1st item has more than 2 bits differing from rest of all the items so it is in Bag 1.
2nd and 5th item have 2 bits differing so they can be grouped together.
3rd and 4th are also having only 2 differing bits so they can also be put into the same bag.
5th is having only 2 differing bits with all others but 1st, so 2,3,4,5 are all grouped together in Bag 2.
Given an array of numbers, only one number appears once, others twice. Find the number. What if two numbers appear once, what if 500 numbers appear once. How to find these numbers.
I know if only one number appears once, we could use xor, but what if more than one? How to do it efficiently?
binary search in circular array?
write a code to check whether a filled sudoku is correct or not?
Algorithm of Level order in tree?
if two digonals of co-ordinates are given then if two rectangles are overlap then return true otherwise false
Given a string Sting="ABCSC" Check whether it contains a Substring="ABC"?
1)If no , return "-1".
2)If yes , remove the substring from string and return "SC".
use very simple code and concept(ALGORITHM)..
You have perfect cubical blocks (i.e. each of the blocks has 6 sides)
You have to make a calender display using those two cubes. So the task is to display the numbers 1 through 31 using the two cubes. For example you would make the date 13th by writing '1' on one cube and '3' on the other.
Only one digit can be written on each face of both the cubes. So there should be 6 numbers printed on each face of the two cubes.
How would you split and write the numbers on the two cubes such that all the numbers from 1 through 31 are displayed using them?
Which one is the faster addressing mode and why?
i).relative addressing mode
ii).absolute addressing mode
Write a program that breaks up a string of words with no spaces into a string of words with appropriate spaces
The amount of Magical Aura is calculated in terms of "Mana Points".
On entering the forest he sees 'n' number of portals in front of him numbered from '0' to 'n-1' arranged in a straight line.
Each portal has a value written over it. He sees that the first and the last portals are damaged and cannot be activated (remain unactivated).
He can perform the following operations repeatedly to gain Magical Aura :
1. He can activate a portal 'x' (obviously not the first and the last one).
2. Let 'l' be the nearest unactivated portal to the left of 'x' and 'r' be the nearest unactivated portal to the right of 'x'.
3. On activating the portal 'x' he gains Mana points equal to the product of value of written over 'l' and the value written over 'r'.
4. A portal once activated cannot be activated again.
He stops when the above process cannot be continued anymore.
Note that 'nearest' is with respect to the portal currently being activated.
Now Sherlock is thinking what is the maximum amount of Magical Aura (Mana points) he can gain in this process.
Help him find this.
Input :
First line contains no of testcases 't'.
Next 't' testcases follow, first line of each is an integer 'n', representing number of portals inside the forest.
Next line contains 'n' space seperated integers which are the values written over the corresponding n portals.
Ouptut :
Output 'n' lines each having one integer denoting the maximum amount of Mana points he can gain for that particular testcase.
Constraints :
1 <= t <= 500
3 <= n <= 80
1 <= Value written over each portal <= 1000
Sample Input :
1
4
1 2 3 4
Sample Output :
12
Explanation :
We have only 2 choices :
1. Activate portal numbered 1 first, and portal numbered 2 next. The total Mana points are 1 * 3 + 1 * 4 = 7.
2. Activate portal numbered 2 first, and portal numbered 1 next. The total Mana points are 2 * 4 + 1 * 4 = 12.
So the answer is 12.
In what situations bubble sort, selection sort, insertion sort, merge sort, quick sort and heap sort will have best time complexity. Provide example for each sort and explain
Implement a timer library.
Given two dates (y/m/d) determine implement a function that determines whether the dates are a month apart.
Implement a garbage collector that avoids the circular dependency problem (graph theory problem).
Design an elevator system for a building. What metrics are useful to determine elevator performance?
Given an array of ints, find all pairs that add up to a target value.
Describe a time you encountered an issue and how you fixed it.
Design a distributed keystore with a single write end-point and multiple read end-points.
What steps are involved in serving a web page to a client?
Copy a linked list with next and arbitary pointer without modifying original linked list i.e. read only linked list.
1000 elements in one bag and 1 million elements in another. how do you find common elements among them. Also give the complexity of your solution.
2.Given an integer linked list of which both first half and second half are sorted independently. Write a function to merge the two parts to create one single sorted linked list in place [do not use any extra space].
Sample test case:
Input: List 1:1->2->3->4->5->1->2; Output: 1->1->2->2->3->4->5
Input 2: 1->5->7->9->11->2->4->6; Output 2: 1->2->4->5->6->7->9->11
C/C++/Java/C#
struct node
{
int val;
node *next;
}
node* sortList(node* list1) {
}
Java
class Node
{
int val;
Node next;
}
Node sortList(Node list1) {
}
Question 3 / 3 (Find first unique character)
Find the first unique character in a Stream. Please note that you are being provided a stream as a source for these characters.
The stream is guaranteed to eventually terminate (i.e. return false from a call to the hasNext() method), though it could be very long. You will access this stream through the provided interface methods.
A call to hasNext() will return whether the stream contains any more characters to process.
A call to getNext() will return the next character to be processed in the stream.
It is not possible to restart the stream.
If there is no unique character, then return the character '#'. # won't be any character in the character stream.
You just have to complete the function getUniqueCharacter() using the functions hasNext() and getNext() which are already defined.
Example:
Input:
aAbBABac
Output:
b
Input:
aBBa
Output:
#
Question 1 / 3 (Odd even level difference)
You are given a function calcDifference which takes in the root pointer of a binary tree as it's input. Complete the function to return the sum of values of nodes at odd height - sum of values of node at even height. Consider the root node is at height 1
Sample Input:
Sample Output
-74
Explanation:
[ (1 + 4 + 5 + 6 + 7 ) ? (2 + 3 + 8 + 9 + 10 + 11 + 12 + 13 + 14 + 15) = -74 ]
Write a class DominoChecker that has a method called addBox(int[]) that takes a box of five dominoes, described as a list of 10 integers (explained after), adds it to a collection, and returns true if a box with the same dominoes was already in the collection and false otherwise. A box of dominoes is encoded as a list of 10 integers from 0 to 9, where a pair of numbers represent a domino. For example: 0,2,9,1,3,3,7,4,5,6 represents a box containing dominoes: (0,2); (9,1); (3,3); (7,4); (5,6). http://en.wikipedia.org/wiki/Dominoes for more basic info (like pictures)
write a program to print a matrix
1 2 3
4 5 6
7 8 9
I need to print like following
1 2 3 6 9 8 7 4 5
Given a matrix of size M X N containing all 0's, and a co-ordinate (i, j) in the matrix.
You have to fill the matrix with L shape block (made by 3 blocks, each block is having 1) except the given co-ordinate.
1 1
1
1
1 1
1
1 1
1 1
1Note - L shaped block can be rotated, so finally there will be 4 orientation for L shape block.
You can assume that solution always exists.
Later on he changed matrix to N X N where N = 2^n.
What are virtual constructors and virtual destructors?
In code there is a breakpoint at the first line of main function. The program is executed but it crashes without touching the breakpoint. Is there any code that is executed before main itself
Find if all the leaf nodes are at same level in binary tree.
Recursive and non-recursive approach?
Design a class for Game of card. You can use any design pattern or data structure.
1. There are 52 card.
2. There are 4 suits, each contain 13 cards.
Given 2 quad-trees find the intersection of black-pixels.
Define a quad-tree for a black and white image. Count the number the of black pixels.
Given a large network of computers, each keeping log files of visited urls, find the top ten of the most visited urls.
(i.e. have many large <string (url) -> int (visits)> maps, calculate implicitly <string (url) -> int (sum of visits among all distributed maps), and get the top ten in the combined map)
The result list must be exact, and the maps are too large to transmit over the network (especially sending all of them to a central server or using MapReduce directly, is not allowed)
Having an infinite stream of numbers write a function to take an element with equal probability for each.
Given a class of block reader, read in unlimited string flow.
You are given a grid, with points on the intersections (think a map of streets, people are standing on random corners). Write code to calculate the point on the grid that is the shortest distance from every point on the grid.
Given a set top box:
a, b, c, d, e,
f, g, h, i, j,
k, l, m, n, o
p, q, r, s, t
u, v, w, x, y
z
Write code to give the character sequence given a word, For example, if the word is "CON", the function will print this:
Right//now we're at B
Right//now we're at C
OK//to select C
Down
DOwn
Right
Right
OK//to select O
Left//now at N
OK//to select N
note: Be careful when you're at Z. if you go to the right, you will get stuck.
Afterwards, the interviewer adds a space to the right of 'Z' to test the code.
Design and implement a class, which returns a random string value from a set with an arbitrary probability distribution given by an array of probabilities. Using an existing random number generator with a uniform distribution(e.g., Random.nextFloat()), you return the string for the random float value based on the strings probability distribution.
You have 13 sorted cards, every cards from "2 ,3, 4, 5, 6, 7, 8, 9, 10, J, Q, K, A".
you can discard all cards, according to some rules:
a pair of cards, like: 2,2
three cards, like: 8,8,8 or 8,9,10; J,Q,K
card A can convert to any cards as you wish, like: A -> 3
For example: Input: 2 2 3 4 5 5 6 7 8 8 9 9 9
you can discard: 2 2
3 4 5
5 6 7
8 8
9 9 9
output:
TURE
Input:
2 2 3 4 5 5 6 7 8 9 10 J A
“A” can be converted to “J”, so
you can discard
2 2
3 4 5
5 6 7
8 9 10
J J
output
TRUE
IN file system count the frequency of a word in descending order ,,plz provide the ans//
L = { <M> | there is at least one input string on which the Turing machine M does not halt}
Here, for a Turing machine M, the notation <M> denotes an encoding, oversome alphabet, of the code of the Turing machine.to
which of the following language classes does L belong:
(1) Regular.
(2) Context-free but not Regular.
(3) Recursive but not Context-free.
(4) Recursively enumerable but not recursive.
(5) Not recursively enumerable.
Sherlock wants to recollect all the clues in his clue box. The clue box is very heavy and cannot be moved. Sherlock doesnt like much burden at once and therefore he will not carry more than two clues at any time. Thus after picking at most two clues, he will need to put them back in his clue box.
Also, if he has taken a clue, he cannot put it anywhere except his Clue box (clues are too important for him to do so).
You are given the coordinates of the "Clue box" and the coordinates of the "clues" in cartesian
coordinate system. Sherlock covers the distance between any two points in the time
equal to the square of the euclidean distance between the points. Also, Sherlock is initially at the same position as his clue box.
Now being a brilliant programmer, you want to help Sherlock. Help him find the minimum time in which he can gather all the clues in his clue box.
Input :
First line contains t, the number of test cases.
First line of each test case contains two space separated integers Xb and Yb, the position of Sherlock's clue box.
Second line of each test case contains N, the number of clues.
This is followed by N lines each containing two space separated integers Xi, Yi which is the position of the ith clue.
Output :
For each test case, output in one line the minimum time required by Sherlock to gather all his clues.
Constraints :
1 <= T <= 100
1 <= N <= 24
-100 <= Xi, Yi <= 100
Sample Input :
2
-3 4
1
2 2
1 1
3
4 3
3 4
0 0
Sample Output :
58
32
It was a pretty interesting question.
Assume that you are given a fixed set of floating point numbers. Now given a new floating point number 'x', the goal is to efficiently find the number that is closest to 'x' from the fixed set. Question is: what data structure will you actually use for storing the fixed set of floating point numbers to achieve this?
Edit:
I missed to add. The interviewer further mentioned that I can not sort and that I can use any amount of time for creating the data structure (meaning this need not be efficient).
Since, I am not allowed to 'sort', I assumed that I can not use BST as I will have to compare numbers while populating the tree. But I didn't clarify it with him; I should have in hindsight.
design a method which consumes an integer and output the corresponding column number in Microsoft Excel ( ex. A, B, C......Z, AA, AB....ZZ....)
Given an array of randomly sorted integers and an integer k, write a function which returns boolean True if a pair of numbers exists in the array such that A[i] + A[j] = k and False otherwise. Provide an O(N) and an O(N log N) solution.
Print the numbers between 30 to 3000.
CONSTRAINT:
The numbers shouldnt contain digits either in incresing order or decreasing order.
FOLLOWING NOT ALLOWED
##123,234,345,1234,2345##increasing order,
##32,21,321,432,3210 etc##decresing order.
FOLLOWING ALLOWED:
243,27,578,2344 etc.,
Now see who ll code ths....
Find largest palindrome in a file without altering the file (like deleting white spaces).
The palindrome def is relaxed - it allows for spaces in between words- do not bother about spaces.
Input : A Perl program file
We need to modify the file to have a max of 80 characters per line and create a new perl file.
Problem is we need to use "/" wherever we split the line and also, the split MUST happen at a place with white space. (ASSUMPTION - No is >75 characters)
Given a string with lower-case and Upper-case mixed, print all the permutation of it under the follow condition: the position of the upper-case letter can not be changed
###Print numbers between 45 to 4578 without repeating digits.###
Ex: 45-ALLOWED;55(repeatng digits)(-NOT ALLOWED. Frnd tld ths 2 me.he tried diff concepts but interviewer wanted an OPTIMAL ONE..LETS C WHO WRITE THIS WITH SIMPLE LOGIC..
Create a QR code reader App without using 3rd party library?
I am familiar with only using some 3rd party library.
Given an n X n matrix, find all elements which are zero, when found set all the elements in that row and column to zero.
Given an array with repetition of numbers .Find the maximum length of continuous subarray with at max 3 unique numbers in O(n).
Eg. A: 123143412
output : 6 (314341)
Given a string with some repeated characters find out all the substrings with only three unique characters.
Given historical data for the stocks of a company for say 8 day. you can buy and sell the stocks just once. Find the maximum profit you can make:
Day 1 2 3 4 5 6 7 8
5 9 6 2 4 8 3 1
Given a string 'aabbcdccefff', find the first Non-duplicate character i.e. 'd'
Use SIMPLE LOGIC for Converting this string str="aaabbccc" into str="3a2b3c".
###Note:###
I gave 3 diff solutions to interviewer with loops,conditions etc.,But he wanted a real OPTIMAL SOLUTION..lets see who ll write!!!!!
given a array of digits. print all combination of of these i.e all no formed by these.
repetition allowed.
and then for modification:
repetition not allowed
example:
i/p:
arr={2,3,4}
o/p:
(without repetition)
234
243
324
342
423
432
Given a positive int "N". and an array of numbers ranging from 0-9 (say array name is arr).
print all numbers from 0 to N which include any number from "arr".
example:
i/p: N=20
arr={2,3}
o/p: 2,3,12,13,20
Given the amazon webpage, if you select any one item, you get recommendations down, for eg:- when I select a book, I get other book recommendations as well as movies related to the book, so If I now click on a movie, then I get something like popcorn which is related to movies, then I get food items as recommendations which is related to popcorn and so on.
So how do find how many clicks it takes to reach a particular item? for eg:- from a book to a pizza
Given a community of people, find out a person who could be a potential mayor. Constraints as below.
1) Mayor does not know any of the people in the community.
2) All the people in the community must know the mayor, that is he has to popular.
My apologies, I forgot to mention that the interviewer had also given me a function called " knows(int a, int b) " that returns a boolean value if a knows b.
create a mirror of a binary tree.
Given a string of text, group all the words such that anagrams are stored and returned together in groups.
Remove duplicates in a string.
find the 3 most repeated numbers in a given array.
Find out the sum of diagonals of matrix(here 2 diagonals)
###Any1 having Better solution?pls i really need this
WITH ALGORITHM (step by step) fr my interview.###
Constraint:
u should use the middle element only once..
matrix
1 2 3
4 5 6
7 8 9
Here 1st diagonal is 1+5+9=15
2nd diagonal is 3+shouldn't repeat(5)+7=15...
There is an array with an input {0,1,2,3,5,6,9} . Write a program to show the combinations for which the sum is 9.
Ex - {3,6} , {0,9} ... etc
Str="4142434546" Findout missing no 44.Add it to str;
Output:"414243444546".
once again i got stucked in this..Help me..
Write a comparator which can be used to compare any type of objects?
Explain a load balancer data structure and algorithm.
Explain a data structure for routing table and matching a route based on longest prefix match.
Given a tree (not necessary a Binary Tree) print (draw) the tree in original structure with proper formatting.
Write a function that takes an unsorted array of integers as a paramater and returns the array without duplications. (Order of returned array doesn't matter as long as ONLY one of each integer in the original array is present).
Given an array of strings. Find the common combination of the strings in the array. Given : There is one combination of the strings in the array that uses all the elements in the array.
For example : Array a = { "abc","efgh","abcde","fgh","abcd","defgh"}; ans = abcdefgh ; Because "abc"+"defgh" = "abcdefgh",
""abcd"+"efgh" = "abcdefgh"
"abcde"+"fgh" = "abcdefgh"
If the parent process creates multiple children using fork() what will be pid of process(getpid) in parent address space?
my understanding is when the parent process creates child process, the parent process get the pid of child. But the question is when parent process creates more than on child what will be the its pid?
Delete a specific char from string,,,,char is 'f' in string= "YOUSUF".the resultant string will be "YOUSU".
A string str ="STUN",, u hav to replace TU by KO . The resultant String "SKON". Use simple logic...
##Pretty much interested question asked in AMAZON Written test##
Take a string, store it as digits; str="678876". Now Check if the given str return TWO EQUAL PARTS with equal sum (6+7+8=8+7+6);if it is correct then replace the str(678876) in the new string, str1="12345876678"
Final output should be: "12345678876"
I tried this ..but the interviewer didnt satisfy..
HOW TO RETRIEVE THOSE EMP NAMES WHO ARE BELONG TO THE DEPT HAVING MAXIMUM EMPLOYEE
Write a function that return a list string which permute all other letters (b to z) by keeping letter aa combination when the size of string is given.
Say n = 4 Output aabb,aabc,aabd..aazz abab,abac,abad..azaz abba,abca,abda..azza baab,baac,baad..zaaz . . bbaa,bcaa,bdaa..zzaa
Say n=5 Output aabbb,aabbc...aazzz ababb,ababc...azazz . . bbbaa,bbcaa...zzzaa
##NEVER SKIP THIS QUESTION..ASKED IN AMAZON###
Take THREE arrays,like arr1={1,3,5,7,9}; arr2={1,2,3,5,4,1,8,9,7};arr3={1,3,5,7,9,2,1,4,6,5,8};Now find out the Duplicates of First two(arr1,arr2) arrays and store it in new another array arr4(should contain only duplicates,no unique elements).Now compare arr3 with arr4.You should return only UNIQUE elements from both of the array.If found, return it, else return -1.
How reverse key index helps in faster data reading and what is use case for this?
Complexity of B tree index?
Explain Hash and how hashing works?
Another question was on why HashMaps stores same hashcode entry in map as linkedlist, why not it is storing as ArrayList?
Explain Quick sort and how to choose Pivot value in this sorting.
Given an array with huge number of elements. Following two operations can be performed on the array at any time
1. Find cumulative sum of first x numbers when x is input by user
2. Add/subtract value 't' from any index i of the array.
Find the most optimal way such that both the above requirements are optimized.
Let f (n) denote the nth term of a sequence of integers given by the equation f(n) = f(n-1) +f(n-2) for n > 2 and f(1) = 1 and f(2) = 1, then using principle of mathematical induction, showthat √ 5 f( n ) = {(1+ √ 5) / 2} n -- {(1 -- √ 5) / 2}n for all n > = 1
str="AB0CD1010" this s a string consider it as a counter variable n increment it
for example the next element should be "AB0CD1011"
Note: If anyone know the answer fr ths ques well,pls post with full code and ALGORITHM(for beginners)...
we create 2 class A, B and we declare 2 variable in Class B . whatever we do change in Class B i want to reflect in Class A ?? How We can Do???
is it possible to call child class fuction through base class object in c++ ??
Add the ODD ORDERED elements in a matrix.But the intersecting(middle) element must be added only once.
Ex:
467
932
148
in this matrix 4,7,3,1,8 are odd indexed or odd ordered elements;We have to add them but,
###constraint ###
intersecting(middle) element must be added(used) only once.
We are given a set of integers with repeated occurences of elements. For Example, S={1,2,2}.
We need to print the power set of S ensuring that the repeated elements of the power set are printed only once.
For the above S, the power set will be {NULL, {1}, {2}, {2}, {1,2}, {1,2}, {2,2}, {1,2,2}}. So, as per the question requirements, we need to print {NULL, {1}, {2}, {1,2}, {2,2}, {1,2,2}}
You are given an integer K, and a sorted array as an input which has been rotated about an unknown pivot. For example, 4 5 6 7 8 9 1 2 3.
We need to write a function which should return the index of K in the array, if K is present, else return -1.
Write a function which returns the square root of a given number upto a precision of 0.0001. Only arithematic operations like addition, subtraction, division and multiplication are allowed.
Rockets are launched until the first successful launching
has taken place.if this does not occur within 5 attempts,the
experiment is halted and the equipment inspected.suppose that
there is a constant probability of 0.8 of having a successful
launching and that successive attempts are independent.Assume
that the cost of the first launching is K dollars while subsequent
launching cost K/3 dollars.whenever a successful launching take place,a certain amount of information
is obtained which may be expressed as financial gain of,say 'C' dollars.if 'T' is the net cost of this
experiment,find the probability distribution of T?
Designing the high level interfaces/abstract classes for a software system
Given a list of 'N' coins, their values being in an array A[], return the minimum number of coins required to sum to 'S' (you can use as many coins you want). If it's not possible to sum to 'S', return -1
Input #01:
Coin denominations: { 5,5,5,5,5 }
Required sum (S): 11
Output #01:
-1
Given a BST. If any of the two nodes value in the tree has been swapped. Find those two nodes and correct the tree.
Implement a Boolean vector: T, F, F, T, F, … with the following operations:
append(boolean b)
boolean get(int index)
set(int index, boolean b)
int length()
Restriction: no Java collections classes
What if you knew the vector has 99.99% T and only 0.01% False. How would you change the approach?
How do you apply Binary Search on 2D array supposed you have 2D array with integers sorted both horizontally and vertically. If you find any occurrence of the value you are looking for you return true else false. What is the complexity?
For example the 2D array could look like the following
Given a binary tree, change the right pointer of every leaf node to the next leaf node (right to it but may be on different level).
A link list contains following elements
struct node{
int data;
node* next;
node* random;
}Given head of such a linked list write a function who copies such a linked list and returns the head of the new list. So if in the original list first node points to fourth node in random the copy should have the same relation. The random pointer can point to any node including itself and more than two nodes can have random pointer to the same node.
Required time complexity O(n) and no extra space can be used (apart from the newly allocated memory which you will need to create the new list)
Write a thread safe data structure such that there could be only one writer at a time but there could be n readers reading the data. You can consider that incrementing or decrementing a variable is an atomic operation. If more than one threads try to write simultaneously then just select one randomly and let others wait
There are n bombs in a big circle,and each bomb has a value and a 'effect range'.If you detonated a bomb,you will get this bomb's value,but a bomb can have effect on the neighbors which the distance(difference between index) between them is smaller than the 'effect range'.It's say that the neighbor bomb will be destoryed and you could not get their values.
You will given each bomb's value and the 'effect range',and you need calculate the max value you can get.
eg. n=3 index 0's bomb' v is 2,range is 0(will not effect others).and v[1]=1,r[1]=1,v[2]=3,r[2]=1;
this case's max value is 5.(detonate the 0's and than the 2's).
HELP ME.
ps: It's a interval DP.
Pgm to compare two strings..Their we have to compare
i) first char at first time.
ii) second char at second time
iii)third char at third time..so on..
My code is : for(i=0;i<str[i].length();i++)//str1
{
for(j=0;j<str[j].length();j++)//str2
if(str[i].charAt(i)==str.charAt(j))
{
printf("yes");
}
else{
printf("false");
}}}
Any more suggestions?
Print our name in pascal triangle..
ex:anony
Add the diagonal elements of a square matrix (of odd order say 3*3,5*5) but the intersecting element must be added only once.
Sorry for my poor english..That what i understood from interviewer..
Given a bst and a group of numbers g, check whether all the elements of g occur in the same path.
Write code to search and return all those file names present in a given directory (for e.g. C:\>) where the string "Amazon" is present. All the files will be located at different folder levels. Also discuss your approach, time and space complexities for your solution.
z=++x+y---++y-x---x---++y-x-- Find the value of z. if x=7,y=-3.
You're given 50 cups of sugar water. Each cup has the same volume but different amount sugar in it. Each cup is labeled with the ratio. Write an algorithm that tells us if it is possible to mix together different cups and get sugar water with perfect 1:1 ratio
given two nodes of a binary tree, find number of nodes on the path between the two nodes.
1
2 3
4 5
4, 3 -> (4-2-1-3): 4Two sorted 2D arrrays, get the third one sorted
A = [["a", 1], ["b", 2]] sorted all elements have different names
B = [["a", 2], ["c", 3]] sorted
C = [["a", 3], ["b", 2], ["c", 3]] sorted
input - 2D array of characters and a text pattern. program to find if pattern is present in array or not. a cell can't be used twice for pattern matching. return 1 if true or 0 otherwise.
eg :
Matrix
{'a','b','c','r','d'},
{'e','f','o','g','h'},
{'i','o','j','k','i'},
{'w','g','f','m','n'},
{'z','a','s','i', 't'}
and search for "microsoft"
Filter Numerics,strings,Symbols,numbers separately from a Alphanumeric string Ex:"Myunite@#$%%^^12334" .
I tried to code 2 ths ques..i hav partial ans..
Design high throughput trading application? Application is hosted in NY and we have traders all over the world accessing this application. What things we need to take care on designing this application.
If we have unsorted list of numbers like
3,1,4,7,9,4,7,4,9
best way to figure out if number n exists in the list? they were interested in constant time performance
Removing duplicates from unsorted list of integer?
if you have unsorted list of
0,5,9,5,6,7,6,9
the result should be
0,5,9,6,7 and the performance should be best over more number of elements.
How to create singleton class and what if the constructor is throwing IOException? what will be best strategy to create instance of this class?
The question is more on constructor throws exception.
//create singleton class.
private SingltonExample() throws FileNotFoundException {
File f = new File("data.txt");
FileInputStream fis = new FileInputStream(f);
}explain if this method is thread safe?
public static void myMethod(StringBuilder sb){
// StringBuilder is not thread safe..
}Given nxn boolean matrix (0's and 1's) .
Find out whether there exist a row i and column j such that
1) all elemets of row i are zero's and
2) all elements of column j are 1's and
3)(i,j)th entry of the matrix can be either 0 or 1
Find out such a i and j exist or not .
complexity :O(n)
Given a 2d matrix with characters and a dictionary. Find non-distinct occurrences of the words found in the array, horizontally, vertically or diagonally, and also the reverse in each direction.
Write a function that takes as its input a integer number of cents
in the American monetary system. Return the count of unique combinations
of coins in the American monetary system that total the input number of
cents. For example, if the input is 6 cents, the output is 2 - you can make
six cents with a nickle and a penny, or with six pennies. If the input
is 11 the output is 4, if the input is 26 the output is 13, and if the
input is 76 you really want a computer to count them all.
The American monetary system has pennies with a value of 1, nickels with a value of 5, dimes with a value of 10, and quarters with a value of 25.
Given below is a tree/trie
A
B c D
e F
a<b<e<>>c<>d<f<>>>
above string represents the following trie/tree (visualize) and assume that there exisits a serialize method that performs above.
Now, write a deserialize method so that above string to an object model of the following
TreeNode
TreeNode[] children
char *p="hello";
Which statement is more efficient to access p[2]? and why.
1) p[2]
2) *(p+2)
---
It should be an interesting question to think over.
Given a 2D array (n x m) of integers, find all duplicate rows and print their index.
int a,i;
(i++)=a;
(++i)=a;
which statement is correct? --explain the reason in the view of compiler.
note: it's not related to initialization or not. say i=2, a=5. I think it is a nice question to test the interviewee's knowledge of compiler.
Write a program to convert decimal to 32-bit unsigned binary.
Find the nearest leaf node from given node in binary tree.
Find maximum product of subarray in given array of integers
Design T9 dictionary
How to iteratively verify if a BST is balanced?
A function to implement a queue using 2 stacks
Given an unsorted set of numbers from 1 to 10 with 2 nos missing, how to find the missing numbers in the set without sorting
A c program to find the largest prime number <=N for any given N
A C program to create the index that you normally find at the emd of a book
A program to randomize/shuffle a sorted integer array of size N
Giiven 2 arrays of integers, find the intersection of those 2 arrays using c program?
A c program to illustrate implementation of a singleton class & how it's instantiated?
A c program to convert 32 bit unsigned decimal number to binary?
Design a web crawler to dump all the pages of a given website (URL) onto disk. So basically it saves pages which is related to the website (for instance dump all pages of aws.amazon.com) and do not crawl the links outside the website
I coded it in python and then they asked what is the internal structure of dict in python and why or why not it is fast
Design a library shelf which can store books or digital media also like CD/DVD. It was more of a design question rather than a coding question and they wanted to know how would you design classes and have abstractions and inheritance in them.. after that they kept on adding details of what could be included on the shelves and how to manage them and routines related to them and what would info I need to have to respond to the user queries and making the design useful.
Test scenarios for gmail application after logging in?
Describe the design of a low latency distributed environment where multiple processes( or threads) need to access shared data structure or a database for a fast ( speaking of a fraction of a milisecond) read or update. You have to process tons of request very quickly ( you can think of market price data as an example, etc). How would you build such an environment in the most efficient way? Describe the solution in details(a few sentences).
Given a weighted directed graph with n vertices where edge weights are integers (positive, zero, or
negative), determining whether there are paths of arbitrarily large weight can be performed in time
(a) O(n)
(b) O(n · log(n)) but not O(n)
(c) O(n1.5) but not O(n log n)
(d) O(n3) but not O(n1.5)
(e) O(2n) but not O(n3)
Given a float number 7.64, convert it into the string WITHOUT using any inbuilt function/library.
If you have a 10G file and only 2G of memory, how can you fit the file into the memory. Describe the solution and write the code.
there is an infinite line.you are standing at a particular point you can either move 1 step forward or 1 step backward.you have to search for an object in that infinite line.your object can be in any direction. Give optimal algorithm.
Given a n (large number) lists of customers who visited n webpages on n (large number) days, design a data structure to get customers who have visited the website on exactly “k” days and should have visited at least “m” distinct pages altogether.
Was then asked to improvise the solution as much as possible
Given a n by m matrix of bits find the largest X that is formed in the matrix and return the size of the diagonal of that X. An X is defined as 2 equally sized diagonals that share a single 1.
For instance, the matrix:
00100001
00010010
00001100
00001100
00010010
00100001
Will return a size of 1, because the given X is invalid as the middle part does not share a single 1. On the other hand, the following matrix
101
010
101
Will return a value of 3, as the diagonal is 3. Write such program,
Given an array of integers . Write an algorithm to find all the Pythagorean triples.
Eg : i/p : int arr[ ] = {1,3,4,5,6,7,8,10,11}
o/p: Print 3,4,5 and 6,8,10
Multiply two linked list represented as linked list and return result as linked list.
Reverse a string without using any temporary variable.
Suppose {{char str[] = "Hello"; then str[] = "olleH";}}}.
I told him we can "shift H to o then o to H", similarly so on. But could able to write the code.
Suppose a linked list (having n number of node) is given to you. You don't have the starting address. I have given you suppose address of "3rd" node.
ptr = Address of 3rd node;Now using only ptr delete 5th node. And at the end of the program my "ptr should have the address of 3rd node". Don't use any temporary ptr and variable etc.
How can a HashMap accepts caseSensitive value ?
Q? How to find the highest nus. and second highest nus from a file ?
There are total of n boxes kept in a single row next to each other .
Each box has weight W(i) .
How to split the boxes into two groups such that the difference between the total weight of the two groups is minimum and
the boxes in each group maintain the order in which they were initially.Also there is a condition that there if the total number of boxes is even ,
then both the groups should have n/2 boxes and if n is odd , one group should have (n-1)/2 and other (n+1)/2 boxes.
for example....
lets say there are 3 boxes of weight 6,12,5.
then the solution would be that one group has 6,5 and other has 12
write a program to find sum of any path from root to leaf such that the sum of all nodes along the PATH is max compared to all other path,,
Given an input array
a={1,2,3,6,2,8----}
product of all numbers=p=a[0]*a[1]*---a[n-1] where n is size of array
output arrau should be b={p/a[0],p/a[1],p/a[2]-----}. you should not use division operator.Time complexity should be less than o(n2).
How to effectively implement and index for facet filtering?
how to find the suitable maze path
Given a array of size n. Divide the array in to two arrays of size n/2,n/2. such that average of two arrays is equal.
You are planning a big programming conference and have received many proposals which have passed the initial screen process but you're having trouble fitting them into the time constraints of the day -- there are so many possibilities! So you write a program to do it for you.
· The conference has multiple tracks each of which has a morning and afternoon session. · Each session contains multiple talks. · Morning sessions begin at 9am and must finish by 12 noon, for lunch. · Afternoon sessions begin at 1pm and must finish in time for the networking event. · The networking event can start no earlier than 4:00 and no later than 5:00. · No talk title has numbers in it. · All talk lengths are either in minutes (not hours) or lightning (5 minutes). · Presenters will be very punctual; there needs to be no gap between sessions. Note that depending on how you choose to complete this problem, your solution may give a different ordering or combination of talks into tracks. This is acceptable; you don’t need to exactly duplicate the sample output given here.
write a program that prints numbers 1 to 100
with most efficient condition
1. Run Time Complexity
2. Run time Space complexity
3. Compilation Time
4. Compile Time Space Complexity
5. Power complexity (reduction of battery used)
A k-palindrome is a string which transforms into a palindrome on removing at most k characters.
Given a string S, and an interger K, print "YES" if S is a k-palindrome; otherwise print "NO".
Constraints:
S has at most 20,000 characters.
0<=k<=30
Sample Test Case#1:
Input - abxa 1
Output - YES
Sample Test Case#2:
Input - abdxa 1
Output - No
What is the minimum representation in bits of two positions on an 8x8 chessboard?
How does a search engine perform exact phrase search? i.e. search for the term "the bees knees" exactly.
There is a fictional company called fooBar in fooLand. The CEO of fooBar, fooMan, directs all managers to minimize the total hike that they give to employees, while ensuring that the hike is fair to them. Usually, this is done by giving more hike to employees who are rated better. So, for example, if an employee is rated 2 and is given hike 3x, an employee rated 3 should be given a hike greater than 3x. Hikes are always in multiples of x only and the minimum hike to be given to any employee is x.
This year, however, a wicked manager, barMan comes up with a brilliant strategy. He assumes that each employee would get to know the hike of only the two employees who sit next to him (one on the left, one on the right). And therefore, he reasons(using whole of his analytical left brain), that as long as he could make hikes fair for each employee with respect to the two employees that sit next to him, he would fulfill the dual objective of being "fair" as well as minimizing the total hike given. Just for clarification, the employees of each team sit in one big line.
barMan hires you to calculate the hike to be given to each employee. Over to you. You are supposed to come up with the total hike number that will excite barMan and make him roll on the floor laughing. You are given that no two employee sitting next to each other would have a common rating.
Input:
The order of rating of each employee should be in the order in which they sit. First line will be the value of x. The second line will be the number of employees 'n'. The next 'n' lines specify the rating of each employee. Rating can be integers from 1 to 105. (weird, right?)
1 <= n <= 105.
1 <= x <= 104.
Sample input 1:
10
4
1
4
6
2
Output:
70
Why?
If we have the hikes as first employee gets 10, second gets 20, third gets 30 and fourth gets 10, we satisfy all our constraints.
A candidate is selected for interview for 3 posts.the number of candidates for the first,second,third posts are 3,4,2 respectively.what is the probability of his getting at least one post?
find subsets in array whose sum equal to a given number??
example: S={1,3,5,2,7} and k=10, answer is {1,2,7},{3,5,2},{3,7}
tks(^_^)
In the given sorted array, find the number of positions of the number that are not in sorted order
Give you an array which has n integers,it has both positive and negative integers.Now you need sort this array in a special way.After that,the negative integers should in the front,and the positive integers should in the back.Also the relative position should not be changed.
eg. -1 1 3 -2 2 ans: -1 -2 1 3 2.
o(n)time complexity and o(1) space complexity is perfect.
There is an sorted array suppose 10 20 30 40 50 60 70 80 90. If we rotate it n times(suppose n = 3 in my case). The array will be 70 80 90 10 20 30 40 50 60. The total no of values which are not in right position 3(in this case which are 70 80 90) so we have to make a generalized solution. I was able to answer this in O(n) but he wants something which is lesser than O(n).
We have a day to work and we have different kinds works do to which has start-time and end-time. We have to choose the different works so that we can achieve the maximum number of minutes in a day to work. Chosen works should not overlaps to each other.
Ex-1:
Start-Time End-Time
W1: 6:00 9:30
W2: 9:00 12:30
W3: 12:00 14:30
W4: 10:00 10:30
W5: 11:00 13:30
Solution: W1 + W4 + W3(or W5)
Ex-2:
Start-Time End-Time
W1: 6:00 8:30
W2: 9:00 11:00
W3: 12:30 14:00
W4: 8:00 9:00
W5: 10:30 14:00
W6: 9:00 11:30
Solution : W1 + W6 + W3 = 390min
Find the expectation value of number of times you need to pick numbers to find a number smaller than the number you pick from a hat containing 1 to n.
case 1: if you replace
case 2: if you don't replace
Expectation values! not probability
There are few sets with some numbers. And you are given an array of numbers. Find combination of sets with minimum number of sets, union of which have all these numbers.
Example:
input sets:
A => [1,2,3]
B => [2,5,8]
C => [1,4,5]
D => [3,5,8]
Array to find:
{3,4,8}
Answer:
C + D
Delete every third element of an array until only one element is remaining. Tell the index of that remaining element in O(1) time complexity.
You are given a sorted skewed binary tree. How can you create a binary search tree of minimum height from it?
Delete the repeated elements in a singly linked list in O(n) time complexity without using extra space. Linked list contains elements in unsorted order
P.S. - Sorting is not allowed
A user creates a file test.sh on a linux system. He wishes to give another user on the same system the permission to execute that file. What permissions should he give to the file?
Write a routine to verify if a given tree is a BST (Binary Search Tree).
Implement cache with proper synchronization.
Flipkart handles millions of users looking to buy or sell products. It also provides a search bar to the user as an interface to search for items. At times when typing users may enter a query string which may be single word by mistake but the intention of the user was to type them separately. For eg.,
User may have entered flipkartmobile when in real, his / her intention was to search for flip kart mobile.
Considering above scenario, implement an algorithm to split up query string provided by user given a list of dictionary words, i.e, you will be given a list of dictionary words and the user-input query string and you have to give the split up of query string which satisfies the following requirements / properties :
1. In case of multiple split-ups, conclude on the one that is lexicographically smaller, i.e, has spaces more towards the left. For eg.,
Assume you are given the list of words : flip, kart, flipkart, mobile and user-input query string is flipkartmobile. Hence, possible split-ups are flip kart mobile and flipkart mobile. The answer / output in this case should be flip kart mobile with more spaces towards the left.
2. Number of characters in query string shall be < 500 characters. Reason being hackers may try to provide a very long input and hence, this may consume processing and result in unresponsive website ultimately.
3. Repetition of dictionary words in query string is possible. For eg.,
Assume you are given the list of words : lg, mobile and user-input query string is mobilelglg. The answer / output in this case should be mobile lg lg.
Now, format of Input and Output :
Input
4 // number of dictionary words given
flip // list of dictionary words the number equaling to input above
kart
flipkartmobile
flipkartmobile // user-input query string
Output
flip kart mobile
The question: given a binary tree, print all paths that sum to a certain value.
I've come up with the following approach (C++). This is different from other solutions I found on the web, that search the path list every time. I would appreciate your opinion regarding my attempt.
// Main function
void print_path_with_sum(Node* root, int expected_sum)
{
if (!root) return;
std::vector<Node*> path;
search_to_bottom(root, path, 0, expected_sum);
print_path_with_sum(root->left, expected_sum);
print_path_with_sum(root->right, expected_sum);
}
// Helper function
void search_to_bottom(Node* node, std::vector<Node*>& path, int current, int expected_sum)
{
if (!node) return;
current += node->value;
path.push_back(node);
if (current == expected_sum) {
print_path(path, 0, path.size());
}
search_to_bottom(node->left, path, current, expected_sum);
search_to_bottom(node->right, path, current, expected_sum);
path.pop_back();
}Why are 2 boot loaders used in Android?
What is the use of each one and is it possible to remove any one of them and boot android?
Note: Two bootloaders are Xloader and Uboot.
#include<stdio.h>
void main()
{
void *p;
int x=10;
float y=20.2;
p=&x;
printf("int %d\n",*p);
*p=20;
p=&y;
printf("float %d\n",*p);
}What is the output?
If error, which error and correct the code.
Given a tree in the form of parent pointers of every node (for root assume parent pointer to be null), write code to find the diameter of tree.
A standard chess knight (it moves in its standard way i.e. L shaped OR 2.5 moves) is sitting at the position a1 on an N x N chess board. What is the minimum number of moves it will take to reach the diagonally opposite corner?
P.S. - If it were a 8 x 8 chess board, the final destination for the knight would be h8
A young girl counted in the following way on the fingers of her left hand. She started calling the thumb 1, the index finger 2, the middle finger 3, the ring finger 4, the little finger 5, then reversed direction calling the ring finger 6, the middle finger 7, the index finger 8, the thumb 9 then back to the index finger for 10, the middle finger for 11, and so on. She counted up to n (to be input by the user). She ended on her which finger?
write an algorithm for, the user request should be completed in logN time in a N story building with M elevators
Given a snake and ladder game, write a function that returns the minimum number of jumps to take top or destination position.
You can assume the die you throws results in always favor of you.
how much memory can calloc and malloc can allocate???
Are the following statements correct in Java.
String firstName = "Joe";
String lastName = new String("Mo");
why can't java have multiple inheritances like c++?
Find the longest sequence in the array.
array = {1, 4, 3, 2, 5, 7, 8, 22}
Answer = 1, 2, 3, 4, 5
In a linked list and loops around and connects to another node(not the first), how do you find the connecting point?
Another question from "Cracking the Code".
If you have a circular linked list, how do you find the middle. You can only go through it once.
Another question from "Cracking the Code".
Sort the array(have to implement the equals method in Cat and Dog).
Cat c = new Cat("Snow Ball");
Dog d = new Dog("Max");
array = {c, d, ... };
You have two threads "A" and "B" and an integer "Count". "A" can increment the count up to 10(stops after that). "B" can decrements the count up to 1(stops after that). Print out the count after increment and decrements.
Count the duplicates in the array ?
array = {"IBM", "Amazon", "Google", "IBM"}
Another question from "Cracking the Code".
Remove duplicates in the array ?
array = {"IBM", "Amazon", "Google", "IBM"}
Another question from "Cracking the Code".
Reverse the values in the array.
Here is the array = {1, 2, 4, 5, 7}
10 45 90 11
23 68 29 09
49 39 23 78
46 92 21 90
Find the largest multiple of 3 consecutive numbers that are in a line
Implement LRU cache.
Given a list of names. Find whether a particular name occurs inside a given tweet or not. If found return true otherwise false Time complexity should be less than O(n).
Ex: "Katy Perry","Ronan Keating" given as a list of string.
List<String> names;
bool findName(String tweet)
{
}
Reverse String Ex: "Hello World" into "World Hello"
Write a function to find 5th element from a singly linked List from the end(not from the head) in one pass.
Write a function to find an first non-duplicate Character from the given String. For example : String "efficiency" has 'n' first non-duplicate character.
DLL contains N nodes of string data in each node...how you will find the combined string of the nodes is Palindrome or not....?
If i create 50 Base Class objects and 50 Derived class Objects, then 50 Base Class Virtual Pointers and 50 Derived class virtual pointers created or Static virtual pointer is created one in Base and one in Derived.....?
Write a function which would take the filename and percentage as the parameters and print out the percentage of contents from the file
printFromFile (String fileName, Integer percentage)
You use the percentage to calculate the percentage of the contents of the file. For example, if the percentage = 50, you read the file and print the 50 percent of the file.
condition1: If you call the file multiple times, the contents you print out should not be the same
condition2: You can' t read in the whole file at once and save it in memory. There is a memory restriction.
I have an array containing duplicates in the following format:
arr[]={ 2,9,1,5,1,4,9,7,2,1,4 }
I want to sort the array in place such that all the duplicate elements are moved towards the end and sorted in different sub arrays like following:
arr[]={ 1,2,4,5,7,9, 1,2,4,9, 1 }
There is no range for integers for the array specified. Following is the code which i tried. This code recursively sorts the subarrays and then move duplicates towards the end. But Complexity wise this is not optimal solution.
Please suggest if it can be solve in O(n) or O(nlogn). Entire code is as follows:
public static int sortDuplicates(int a[],int start,int end){
int i, k,temp;
if(start==end)
return 1;
Arrays.sort(a, start, end);
k = start;
for (i = start+1; i < end; i++) {
if (a[k] != a[i] && a[k]<a[i])
{
temp=a[k+1];
a[k+1] = a[i];
a[i]=temp;
k++;
}
}
return sortDuplicates(a,k+1,a.length);
}How answer is coming as zero instead of garbage? Does compiler sets "0" to uninitialized variable?
#include<stdio.h>
void fun(void *p);
int i;
int main()
{
void *vptr;
vptr = &i;
fun(vptr);
return 0;
}
void fun(void *p)
{
int **q;
q = (int**)&p;
printf("%d\n", **q);
}Write a method to determine if two strings are anagrams of each other.
e.g. isAnagram(“secure”, “rescue”) → false
e.g. isAnagram(“conifers”, “fir cones”) → true
e.g. isAnagram(“google”, “facebook”) → false
Write code to reconstruct the tree from given any 2 traversals.Do it iteratively.
Rearrange an array using swap with 0.
You have two arrays src, tgt, containing two permutations of the numbers 0..n-1. You would like to rearrange src so that it equals tgt. The only allowed operations is “swap a number with 0”, e.g. {1,0,2,3} -> {1,3,2,0} (“swap 3 with 0”). Write a program that prints to stdout the list of required operations.
Practical application:
Imagine you have a parking place with n slots and n-1 cars numbered from 1..n-1. The free slot is represented by 0 in the problem. If you want to rearrange the cars, you can only move one car at a time into the empty slot, which is equivalent to “swap a number with 0”.
Example:
src={1,0,2,3}; tgt={0,2,3,1};
A teacher wanted 100 gems distributed in 7 purses such that number of gems in 7 purses should always sum up to 100. But his condition was that he can demand any number of gems between 1 to 100 and Shiva must be able to satisfy his demand without needing to open any purse. Also once Shiva packs the purses, he will not get another chance to rearrange the number of Gems in those 7 purses. So consider that these purses are sealed the moment Shiva puts appropriate number of Gems in it.
Out of affection, the teacher decided to step up the difficulty level so that Shiva can survive the turbulent world outside the Gurukul. The Guru added one more condition that out of 7 purses Guru will always fill one purse with any number of gems. Thus Shiva need to distribute remaining Gems in rest of the 6 purses.
As a new techie your task is to write a computer program to help Shiva in fulfilling his Guru's demand.
its easy but still!!
find the largest subarray with equal number of 0's and 1's.
example 001010101
output:8
int subarray(int arr[],int n)
{
int count=0;
for(int i=0;i<n;i++)
{
if(a[i]==0)
count++;
else
count--;
}
if(count==0)
return n;
else
{
if(count>0)
return n-count;
else
return n+count;
}
}Consider a hash table with M slots. Suppose hash value is uniformly distributed between 1 to M, and it uses linked list to handle conflicts (if two keys hashed to the same slot). Suppose we put N keys into this M-slotted hash table, what is the probability that there will be a slot with i elements? i could vary from 0 to N.
print the numbers without repeating digits in it and with in the range x to y.
ex. range 50 to 5000,
then it must print like 50,51,52,53,54,56,....57,......65,67,....76,77....109,120,123,124...4987.
not like 556,55, .avoid duplicate digits in number.
Given a BST convert it into new Data Structure that satisfies following conditions:
1. every leaf node's left ptr point to its parent and right ptr points to the next leaf
2. every non leaf node's left ptr points to its parent and right ptr is NULL
3. return the head and print the new DS
example:
7
/ \
5 9
/ \ \
4 6 10
output:
head->4->5->7
|
->6->5->7
|
->10->9-7
with optimal time and space complexity
Given an array, return true, if it can be partitioned into two subarrays whose sum of elements are same, else return false
Example:
Input: {5,1,5,11}
Output: true (as it can be divided into {5,1,5} {11} where 5+1+5=11)
Given a string of numbers in sequence order. find the missing number.Range is not given.
sample input:"9899100101103104105"
Answer:102
Design a stack in such a way that the operations Push, Pop and Find Minimum can be done in O(1). Assume space as not a constraint.
Given an array write a function to print all continuous subsequences in the array which sum of 0.
e.g:
Input:
Array = [-1, -3, 4, 5, 4]
output:
-1, -3, 4
Given an array write a function to print all triplets in the array which sum of 0.
e.g:
Input:
Array = [-1, -3, 5, 4]
output:
-1, -3, 4
Conway's game of life on a grid
write the object model of a json structure
given a crosscut in an island with buildings of different heights with water collecting on top of the island how much water is collected on the island
squarest possible container to house n number of squares
c program to find square root of an interger without using in built functions
A special type of tree is given, Where all leaf are marked with 0 and others are marked with 1. every node can have 0 or at most 2 nodes. Trees level order traversal is given give a algorithm to build tree from this traversal.
Given an array, with positive and negative integers, arrange it in such a way that, positive numbers occupy even positions and negative numbers occupy odd position. All the remaining extra positive or negative integers should be stored at the end of the array. Remember, the elements of the array should remain in the same order.
EG: Input array {1,-2,3,-4,-5,-6,-7,8,9,4,10,11,12}
output array {1,-2,3,-4,8,-5,9,-6,4,-7,10,11,12}
Given a 2D array of strings : A[][]={ fog, fool, food, fruit,for}.
Find a substring such that after removing this substring from beginning of all the strings in A , the length of remaining strings + length of substring is minimum.
example:
if substring is "f" then total length= 1+{2+3+3+4+2} = 15
if substring is "foo" total len is= 3+{3+1+1+5+3}=16
if substring is "fo" total len is= 2+{1+2+2+5+1}=13
since minimum is 13 so output should be "fo"
What happens when "new" fails to allocate memory.
I answered as, it will return NULL. But he was not sastisfied.
What happenes when the "new" operator fails to allocate the memory from the heap?
I answered it will return NULL. But still he was unhappy...
How do you dynamically allocate memory for an integer array of 10 bytes?
Given an array of positive integers, create another array of the same integer such that in the new array the integer at index i is the integer with highest frequency in the input integer.
input array: {1,2,3,6,1,3,6,7,3,9,4,2}
output: {1,1,1,1,3,3,3,3,3,3,3}
find the maximum no. of paths from (0,0) to (m,n) in a m*n matrix
Check if a singly linkedlist of Integer is a palindron or not.
Extraspace: O(1)
Considering a stream of integers coming in. Design a datastructre to store only n of them. Insert if if does not exist in the datastructre. And if it reaches n, remove the first one inserted into the datastructure.
Datastructure should provide, addition, deletion and search all in O(1) time.
Given 3 Arrays of integer sorted in ascending order, get the sum of minimum difference using one element from each array.
where a, b, c are the elements from each array.
diff = |a-b| + |b-c|+|c-a|
complexitiy: worst case O(n)
how to merge two binary search tree into balanced binary search tree.. Let there be m elements in first tree and n elements in the other tree. Your merge function should take O(m+n) time with in constant space.
Examples:
A Balanced BST 1
90
/ \
70 110
A Balanced BST 2
60
/ \
5 800
output :-->
70
/ \
60 90
/ \
5 800
The question was that you need to implement virtual directory using dynamic structure . For example :-
VIT is the root directory then
VIT>CS
VIT>Building Science
.
.
Then each department should have its branch
VIT>CS>CSE
VIT>CS>IT
VIT>CS>MCA
Furthermore each branch will have a number of files i.e
VIT>CS>CSE>file1.txt
VIT>CS>CSE>file2.txt
VIT>CS>IT>file1.txt
Note-No need to create actual files just store the name .
Each file should have properties :-
1) RO(Read Only) or WO(Write Only)
2) Hidden or Visible etc.
List of Commands :-
1) addFile(<file name>) to add file
2) addHiddenFile(<filename>) to add hidden file
3) setReadOnly<filename> to set read only property
4) gotoDir to go to a particular directory
5) listFiles to list files
6) listAllFiles to list all files including hidden files
7) details to display all details of files
8) delete to just to mark the file as deleted but you don't need to actually delete it.
I used nested structures to implement it. Can anyone give a more proper solution with the code?
Create an array from unbalanced binary tree, such that it should re create the same tree again.
what is the data structure used to build a text editor
create the mirror tree for the given BST, provided with the root node of the tree
reverse the doubly linked list without using extra space
Find lowest common ancestor of two nodes in a binary tree iteratively. Root in the binary search tree is not given.
Design a System Which contains multiple components, And all components are in same Assembly. All These Components are independent.
Design a Communication System such that:-
a. Sender is Not Aware of Reciever
b. Any New Component Addition Should Not Change the System Implementation.
( I Guess Interviewer also Not aware What he was asking ;) :P When he told sender is not aware if receiver hehehe)
2. Design a System to Handle Different Type of Objects
And Perform an Operation on the Sender Object.
a. Design to scale , it should handle huge number of Different kind of objects.
Find Whether a Input string had Palindrome?
Example :
Input Samples : "1234xyzyx5678" , "abcdefeabc"
Output : A Bool Value, True if Contains a Palindrome , False otherwise. ( In this Example input string conatins "xyzyx" and efe" Palindrome respectively)
Design a Sudoko Game.
Write a program to find if sum of any two numbers of array is equal to SUM(given as argument). return 1 if it exists else return 0.
An integer n ending with 3 always has a multiple with all 1's. For example 3 has a multiple 111111, 23 has a multiple 11...11. Write a function that takes an integer n and returns string which is the smallest multiple of the n with all 1s
Findind LIS(longest increasing subsequence) in a circular buffer.
Example 5 4 3 2 1 answer is 2(1,5)
Another example 5 6 7 1 2 3 answer 6(1,2,3,5,6,7)
Given a directed labelled graph in form of a knowledge base, and a query, write a parser which can return the edges and/or nodes requested in the query. (Knowledge base and queries are not case sensitive)
Knowledge base is given as input in a text file (input.txt).
For example a DAG can be represented as:
And the corresponding knowledge base for this DAG is :
(<Shelden>, <hasFriend>, <Raj>)
(<Shelden>, <hasFriend>, <Leonard>)
(<Shelden>, <worksAt>, <Caltech>)
(<Leonard>, <worksAt>, <Caltech>)
(<Raj>, <worksAt>, <Caltech>)
(<Raj>, <age>,“30”)
[Here 30 is a number and no edge can go out from this node while others like Nabraska, New_Delhi are entities, which can have further outgoing links.]
(<Leonard>, <hasFriend>, <Penny>)
(<Penny>, <bornIn>, <Nabraska>)
(<Raj>, <bornIn>, <New_Delhi>)A query can be written as :
Find persons who are friends?
Test case 1 : Select ?person1 ?person2 where { ?person1 <hasfriend> ?person2. }
The goal is to fill all the variable represented by ? with their values from knowledge base and return in csv format:
The result of this query is:
Person 1 Person 2
Shelden Raj
Shelden Leonard
Leonard Penny
The similar query can be extended to have joins also:
Find persons who are friends with Sheldon and the company/colleges to which his friends belong?
Test Case 2 : Select ?person ?university where { <Sheldon> <hasFriend> ?person . ?person <worksAt> ?university. }
Person University
Leonard Caltech
Raj Caltech
Test Case 3 : Select ?person1 ?person2 where { ?person1 <worksAt> <Caltech> . ?person2 <bornIn < Nabraska> . ?person1 <hasFriend> ?person2 .}
Person 1 Person 2
Leonard Penny
Test Case 5 : select * where {}
Output : Parse Error
How to approach this problem?How to find medium of 1 billion numbers across N distributed machines efficiently?
Given an array of integers, we have to print all the sub sets of the array which have sum >=k.
For example, If my array is {1,2,3,4,5}
and my k= 5, then the sets I have to print are,
{5}, {4,1}, {4,2},{4,3}.......{1,2,3,4,5}.
Given 2 Arrays made up of 0's and 1's and of equal length. Find index m and n, such that m and n are farthest apart but contain equal number of 0's and 1's.
You are required to parse the xml file:
<ledger>
<person>
<name>Jai</name><location>Bangalore</location>
</person>
<entries>
<entry><day>1</day><credit>50</credit><debit>40</debit></entry>
….
…
multiple entries were there, and multiple people were there.
We were required to validate the XML file.Open and Close tags matching.
We were required to parse, maintain the max balance for each person, the longest span of days each person had the max balance, and report queries such as who had the overall max balance , his span and location. Span must contain the day numbers, not length.
I have a list of several million words unsorted.
How can you find the largest and the smallest words that can be typed by a single hand on a qwerty-style keyboard? Following the rules of finger placement, a word can either be typed fully on the left-hand side of the keyboard, the right-hand side, or both. Find the largest and smallest left-hand word(s), and the largest and smallest right-hand word(s).
given: millions of words, unsorted
given: set of left-hand chars - a,s,d,f,...
given: set of right-hand chars - j,k,l...
The interviewer asked about HashMap, LinkedList, ArrayList. And the coding question was 'given a binary tree, find out repetitive numbers from the binary tree and insert into a list.'
How can we decide whether the two strings are anagrams?(in efficient way)
Given 2 binary arrays A and B i.e. containing only 0s and 1s each of size N.
Find indices i,j such that Sum of elements from i to j in both arrays is equal and j-i (i.e. the length of the set i,j) is the maximum possible value.
Find the majority element which occurs more than n/2 times in an array of n size, which contains duplicate elements in minimum time and space complexity.
Use iteration to find the common ancestor of two nodes on a BST.
Requirements:
1>client should be able to create shapes like circle, square , rectangle..etc,. Also framework should be able to add some more shapes later.
2> client should be able to calculate areas of each shapes
3> should have collection where all shapes are stored and should be able to sort on the area of the shapes
In a Binary Tree, weight of each node is described by the value of the node multiplied by the level (i.e. for root node value is 1* value in root node), And the weight of tree is sum of all the node weights.
Find the minimum tree weight out of all the binary trees possible from a given set of numbers.
P.S: No input and no sample data provided
Given a set of N points with x,y cords in a 2D plane. Find all possible squares that can be formed with vertices in this set.
How would you weigh an aeroplane
Where could we use deadlock? The interviewer was very clear about his question. The use of deadlock.
In which scenario could we use deadlock?
What is the difference between paging and swapping?
In windows OS, "My Computer", we see the option of paging, what does that mean?
When we click on the power button of our Laptop, what happens immediately and how the windows is loaded?
Two arrays are given. Data from both the arrays have to be taken and put into the third array and this third array should have only unique elements. Implement this without using set.
What is the difference between MVC and Factory pattern?
How does the print operation work when we try to give a print from a word document?
What is the use of software that comes along with the printer?
How the data is printed after we click on the print button?
What logic is applied for the data to be transferred to the printer?
What is the logic that makes the printer print the data on a sheet of paper?
I have to create 5 threads where each thread has to perform the addition operation.
Thread1 - Add 1 to 10
Thread2 - Add 1 to 50
Thread3 - Add 5 to 15
Thread4 - Add 10 to 20
Thread5 - Add 15 to 20
What is the best way to accomplish this?
Also, I need 1 sec time delay between each addition operation.
There are two interfaces B and C each having the same method public m1()
class A implements B and C
If class A has to implement method m1, the implemented method would be of which interface?
A method takes two array list as its arguments
Both ArrayList have list of objects similar to the example here below
AL1 = {A,A,B,L,C,F,D,E,F,D,Z,R}
AL2 = {C,E,X,Z,M,X,P,L,M,N,S,T,P,B,A}
The aim is to create a third arraylist AL3 which would contain only elements that are occuring exactly twice, even after combining both AL1 and AL2.
So, the resultant list should be as seen here below
AL3 = {B,C,F,D,Z,E,X,P,M}
What logic do we follow?
There is a stream of numbers coming in and you have to find K largest numbers out of the numbers received so far at any given time. Next problem is that a constraint is added. memory is limited to m. m < k. How would you achieve the goal still.
Given a floor in a building, we need to place tiles on it.
*You can use tiles of a given set of dimensions*. But each type of the tile has a given cost associated. (you cannot cut a tile). How would you tile the floor in minimum cost ? Also answer whether the floor can be tiled at all or not ?
C program to Delete a node from SLL, in which the last node points to the middle node( in case of even no of nodes, it points to the first middle node) and update the SLL.
Given a preorder sequence from a Binary Tree, how many unique trees can be created from this? (They want a recurrence relation and start with the easy cases):
T(0) = 1
T(1) = 1
T(2) = 2
What is T(N) ?
Given a Set of jars of candies, what is the number of ways of getting a pair of candies such that they belong from different jars.
For example given {{1,2}, {3,4}, {6}}. The answer is 8({1,3},{1,4},{1,6},{2,3},{2,4},{2,6},{3,6}, {4,6}).
Given a postorder traversal of binary tree where leaves are represented by small case characters while others are represented by Capital Letters.You have to find the number of traversals from root to all the leaves in which a given Sub-sequence occured.
given an input array of integers where each integer represent the maximum amount of jump a frog can take.Frog has to reach the end of the array in minimum number of jumps.
Example:[1 5 4 6 9 3 0 0 1 3] answer is 3 for this.
[2 8 3 6 9 3 0 0 1 3] answer is 2 for this.
Any DP solution for this?
Given an array of n numbers with repetition of numbers. You need to find the max length of continuous sub array with at max 3 unique elements.
For eg
array: 1 2 3 1 4 3 4 1 2
ans: 6 (3 1 4 3 4 1)
Solution: Time complexity O(n)
Extra Space O(1)
Write a program to swap every two nodes in a linked list . IF the number of nodes is odd then retain the last node.
You are given two array, first array contain integer which represent heights of persons and second array contain how many persons in front of him are standing who are greater than him in term of height and forming a queue. Ex
A: 3 2 1
B: 0 1 1
It means in front of person of height 3 there is no person standing, person of height 2 there is one person in front of him who has greater height then he, similar to person of height 1. Your task to arrange them
Ouput should be.
3 1 2
Here - 3 is at front, 1 has 3 in front ,2 has 1 and 3 in front.
Find all pairs of numbers in an array that sum to a given number, n, in linear time
Design an LRU cache
Design and describe the classes you would use when implementing the card game War.
Given a n (large number) lists of customers who visited n webpages on n (large number) days, design a data structure to get customers who have visited the website on exactly "k" days and should have visited at least "m" distinct pages altogether.
test cases for railway portal??
/*
Random set of WORD.
Criterion : Given a word find out if the word can be broken into smaller word, by removing one alphabet at a time.
a) all such word should be valid dictionary word.( Assume a function is there to test whether the word exist in dictionary)
b) Remove one alphabet at a time but the new word need to be in dictionary.
For eg :
restated -> restate -> estate -> state -> stat -> sat -> at -> a
fullfill the criterion. ( single alphabet assume belong to dict)
My solution below. I assume it can be done using dynamic programming or trie data structure
*/
test cases for railway portal
test cases for atm
n1 pairs of “{} ” brackets
n2 pairs of “[] ” brackets
n3 pairs of “() ” brackets
find the all valid combinations of all the pairs.
Convert a base 2 number to a base 4 number
I have heard this question many times in microsoft interviews. Given two arrays find the intersection of those two arrays. Besides using hash table can we attain the same time complexity that is O(m+n) by using some other approach.
Difference between virtual memory and main memory?
How virtual memory works??
What is the difference between a process and a thread?
After this-> why can you run multiple threads but not multiple processes
How will you sort an array if all the elements in the array cannot be accumulated in the RAM at once i.e the size of the array is larger than the size of RAM
Excel columns are labelled alphabetically in length-lexicographic order, i.e., A, B, C, ..., Z, AA, AB, ....
Given the 1-based numeric index of a column, return the corresponding label.
Example 1:
1
Output 1:
A
Example 2:
54
Output 2:
BB
WAP to find the number of 2s between o and n
e.g
Input = 10
Output = 1
Input = 20
Output = 3
Output the leftmost element of each level of a tree
Suppose there is a new alphabet, eg. the original alphabet is (a b c d ...x,y,z), and the new one is (e k f a ....,o,p,q). Given file in which each line contains a single word and the words are sorted in the new alphabetic order.
e.g., a possible file according to the new alphabet is:
ek
kq
fo
fp
fq
aj
Use the file to reconstruct the new alphabet for as much as possible.
Alex is standing on the top left cell (1,1) of a n*m table. The table has n rows and m columns. Initially, he is facing its right cell. He moves on the table in the following way:
>He moves one step forward.
>He turns to his right
>While moving forward, if he would go out of the table or reach a visited cell, he turns to his right.
He moves in the table as much as he can. Can you find out the number of cells he visits before he stops?
For example, given a 9x9 grid, the following would be his moves. The number on each cell represents the step he would land on that particular cell.
1 2 55 54 51 50 47 46 45
4 3 56 53 52 49 48 43 44
5 6 57 58 79 78 77 42 41
8 7 60 59 80 75 76 39 40
9 10 61 62 81 74 73 38 37
12 11 64 63 68 69 72 35 36
13 14 65 66 67 70 71 34 33
16 15 20 21 24 25 28 29 32
17 18 19 22 23 26 27 30 31
Input:
The first line of the input contains two integer numbers n and m.
n and m are between 1 and 100.
Output:
Print an integer to the output being the answer of the test.
Sample input #00:
3 3
Sample output #00:
9
Sample input #01:
7 4
Sample output #01:
18
We have a rectangle with n rows and m columns filled with numbers from 1 to n*m.
Cell (i,j) of the rectangle is important iff:
* i = 1 and j = 1 (or)
*there is an important cell (a,b) such that (a,b) is a neighbor of (i,j) and the number
on (i,j) is greater than number on cell (a,b) and all of (a,b)'s neighbors except for (
(i,j) itself
Two cells are considered to be neighbors if they share a common edge between them.
Unfortunately the number in some of the cells has been erased. We want to write a number to those cells such that the resultant rectangle has all the numbers between 1 to n*m and it contains as many important cells as possible. In case there are several ways to do that, we are interested with the rectangle which is lexicographically smallest.
A table is lexicographically smaller that the other if the string of its row-major view is lexicographically smaller than the other.
Input:
The first line of the input contains two integers n and m, Each of the next n lines contains m tokens. Each token is either an integer between 1 and n*m or '?'.
Output:
Print the maximum number of important cells that can be obtained in the first line of the output and print the rectangle in the next n lines.
Constraints:
1 <=n,m <=6
Sample input #00:
2 3
2 ? ?
? ? 3
Sample output #00:
3
2 1 4
5 6 3
Sample input #01:
6 6
? ? ? ? ? ?
? ? ? ? ? ?
? ? ? ? ? ?
? ? ? ? ? ?
? ? ? ? ? ?
? ? ? ? ? ?
Sample output #02:
24
1 2 3 13 14 15
4 6 8 10 11 16
5 7 9 12 19 17
28 26 24 22 20 18
29 27 25 23 21 36
30 31 32 33 34 35
We have a rectangle with n rows and m columns filled with numbers from 1 to n*m.
Cell (i,j) of the rectangle is important iff:
* i = 1 and j = 1 (or)
*there is an important cell (a,b) such that (a,b) is a neighbor of (i,j) and the number
on (i,j) is greater than number on cell (a,b) and all of (a,b)'s neighbors except for (
(i,j) itself
Two cells are considered to be neighbors if they share a common edge between them.
Unfortunately the number in some of the cells has been erased. We want to write a number to those cells such that the resultant rectangle has all the numbers between 1 to n*m and it contains as many important cells as possible. In case there are several ways to do that, we are interested with the rectangle which is lexicographically smallest.
A table is lexicographically smaller that the other if the string of its row-major view is lexicographically smaller than the other.
Input:
The first line of the input contains two integers n and m, Each of the next n lines contains m tokens. Each token is either an integer between 1 and n*m or '?'.
Output:
Print the maximum number of important cells that can be obtained in the first line of the output and print the rectangle in the next n lines.
Constraints:
1 <=n,m <=6
please read full question before ans,
time complexity to merge k sorted arrays of size n each where space is not constraint and merge them with in m swap( m is total no of element i.e m=k*n )
Example:
Input:
k = 5, n = 4
arr[][] = { {3, 33, 55, 71},
{29, 63, 64, 88},
{100,999, 1100, 1800}
{18,99, 155, 180}
{360,480, 590, 620}} ;
Output: 3 18 29 33 55 63 64 71 88 99 100 155 180 360 480 590 620 999 1100 1800
==> ( " sort this array with in 15 swap or insertion ")
In QTP automation, how the recorded scripts can be changed when there is an updation in the functionality. And how can we find the particular script to be changed.
Tell me the unique and critical defect you have identified till now and tell me your experience if you faced chanllenges with Dev team.
Open Google.com and now tell me what are the various types of Testing type you can think of to Test Search Edit Field box
ex: Functionality Testing, Security Testing, Load Testing etc
Now list down the various possible scenarios for each type of testing you can think of.
toggle the given length of bit in 32 bit integer.
lets say ,i want to toggle 11-15 bit in 32 bit integer.
We have two strings: a normal alphanumeric string and a pattern string. the pattern string can be composed by alphanumeric chars plus the char "?" and "*"
We want to check if the first string match the pattern, where the ? means that every char (alphanumeric) is permitted in that position, while * allows to have a sequence of alphanumeric chars.
as test we want to check that the function returns true to the following calls.
isMatching("abab","abab")
isMatching("abab","a**b")
isMatching("ababab","ab*b")
isMatching("","*")
isMatching("aaaaaab","*?*b")
i found this question hard, since the language we want to parse is not L1 (there's an ambiguity in the parsing tree) it means that a backtrack modality must be implemented.
Took me a while to find a reasonable solution (that, to be honest i was not happy with)
function isLegal(string:String,pattern:String):Boolean{
if(pattern.length == 0 && string.length == 0)
return true;
if(pattern.length == 0 && string.length > 0)
return false;
// NOT PROUD OF THE FOLLOWING CONDITION
if(pattern.length == 1 && string.length == 0){
if(pattern.charAt(0) == "*") return true;
}
if(isLetter(pattern.charAt(0))){
if(string.charAt(0) == pattern.charAt(0)){
// CHAR BY CHAR CONTROL
return isLegal(string.substr(1),pattern.substr(1));
}
return false;
} else if(pattern.charAt(0) == "?"){
if(isLetter(string.charAt(0))){
// RECURSIVE CALL
return isLegal(string.substr(1),pattern.substr(1));
}
return false;
} else if(pattern.charAt(0) == "*"){
var possibleSolution:Boolean = false;
for(var i:int = 1; i< string.length && !possibleSolution;i++){
possibleSolution = isLegal(string.substr(i),pattern.substr(1));
}
return possibleSolution;
} else {
// ILLEGAL PATTERN
return false;
}
}
function isLetter(s:String):Boolean{
return s.charCodeAt(0) > 96 && s.charCodeAt(0)<122;
}A array of N elements, we have to replace all the elements with nearest greater which is present on the right side of that elements. O(n) is required
U are given a set of strings, using the characters of the given string, the program needs to find the maximum length string that doesn't has any of the given string as its sub-string. In case, if we can have infinite long string satisfying the property, print -1.
I solved this, but looking forward to some convincing algo.
eg 1:
11, 00
longest: 010101010101010101010101... (-1, as infinite long)
eg2
101, 111, 00, 110
longest:010(i think, maybe wrong)
write the jquery for simultaneous dropdown and pagination i.e. we have 500 rows in a table and we want to display those rows. pagination will be used and also dropdown means if no of rows to be displayed is 10 per page then 10 rows per page should be displayed and dropdown changes should go with pagination.
Given a dl representing the spiral level order traversal of a binary tree,convert it to a binary tree using one stack. In Last level, nodes will be either to the right or left only. complete code in C. It is usually done using two stacks. Can it be done using one stack?
Convert ip address(32-bit) into string format.
negate each bit of 32 bit integer. I answered with XOR with FFFF but interviewer asked will ~(number) work? I answered as no.
I executed this piece of code
int x=8;
int k=~(x);
printf(%d",k)
output: 9
x=1000
~(x) =9 how?
Consider the problem of sorting in ascending order of an array of numbers where each number is in the range 50000 to 50000000. What sorting algorithm is the best choice for the above problem. What is the best case time complexity of sorting available to this problem.
Options are:
a. Merge Sort
b. Insertion Sort.
c. Quick Sort.
d. Counting Sort.
e. Bubble Sort
what is difference between array of pointers and pointer to an array?
WRP to determine if a IP address belongs to a network.
The interviewer expected details about subnet masking
Given array of words, group the anagrams
IP:{tar,rat,banana,atr}
OP:{[tar,rat,atr],[banana]}
From a given integer array values, find if a Total value is possible or not? The numbers in the array can be used more than once.
example
int[] points = {3, 7};
isScorePossible(points, 10) => true
isScorePossible(points, 9) => true
Design a parking meter.
A string is called sstring if it consists of lowercase english letters and no two of its consecutive characters are the same.
You are given string s of length n. Calculate the number of sstrings of length that are not lexicographically greater than s.
Input format
The only line of input contains the string s. It's length is not greater than 100.
All characters of input are lowercase english letters.
Output format:
Print the answer of test modulo 1009 to the only line of output.
Sample input:
bcd
Sample output:
653
A lot of transistors contains 0.6 percent defectives. Each transistor is subjected to a test that correctly identifies a defective but also misidentifies as defective about two in every 100 good transistors. Given that a randomly chosen transistor is declared defective by the tester, compute the probability that it is actually defective.
You have a machine that can create anything. You just have to specify the details, and voila, it will give you the output. Design test cases for such a machine
Problem of concurrent transactions done by two persons of a joint account at two different ATM Machines. How is it managed without introducing any inconsistency in balance of the account holders?
Two airline companies, Kingfisher and Jet airways want to do a merger. Design a database migration scheme, so that no inconsistencies and redundancy occur. Assume suitable data and brief on the problems you might face.
Given an equation in the form 2^i * 3^j * 5^k * 7^l where i,j,k,l >=0 are integers.write a program to generate numbers from that equation in sorted order efficiently.
for example numbers from that equation will be in the order 2,3,5,6,7,8,9.....and so on..
There are 6 pairs of black socks and 6 pairs of white socks.What is the probability to pick a pair of black or white socks when 2 socks are selected randomly in darkness.
There are three persons A,B,C .A shots the target 6 times out of 7 shots .B shots 4 out of 5 shots .Then what is the probability of hitting the target twice when 2 persons are selected at random.
Regular expression- String matching. Find as many as patterns found in the given text.
Pattern is "abcd\\d*abcd". Here the regular expression part is ‘\\d*’. Search for this pattern in a text like follows.
text = "KABabcd123abcsdjhsdh". Using above regular expression pattern, we can match a string 'abcd123abcd 'in the text.
More explanation: In the pattern, if it is a '*',then digits can be repeated. If it is a '+', then only one digit.
There is a function which will return whether it is a digit or Char.
public static Boolean IsThisADigitChar(char input). Use this function to find whether the input character is Digit or not.
example: abcd\\d*abcd==> abcd123456abcd is matched
abcd\\d*abcd==> abcd12abcd is matched
abcd\\d*abcd==> abcd1abcd is matched
abcd\\d*abcd==> abcd123456bcd is not matched
abcd\\d+abcd==> abcd1abcd is matched
abcd\\d+abcd==> abcd2abcd is matched
abcd\\d+abcd==> abcd7abcd is matched
abcd\\d+abcd==> abcd123456abcd is not matched
Write a program to find whether two lines are intersecting.
Given a set of n integers and sum of all numbers is at most K. find the subset of these n elements whose sum is exactly half of the total sum of n numbers;
Longest increasing subsequence:
Given n numbers A1..An determine subsequence of maximum length values in the subsequence form a strictly increasing sequence.
ex: input 5,2,6,3,4,1,9,9,8,9,5
output: 2,3,4,8,9
Given a sequence of numbers A(1) ..A(n), find the continuous subsequenceA(i)..A(j) for which the sum of elements is maximum.
condition: we should not select two contiguous numbers
given a matrix of size m * n, place k students in such a way so that cheating in an exam could be minimized
Given notes of different denominations ( 1,2,5,10) , WAP to find in how many ways can you make an amount ‘x’ ?
Given infinite array in which the first n cells contain integers in sorted order and rest filled with symbol $. Assume we don't know n value. Give algorithm that takes an integer k as input and finds a position in array in O(logn)
Implement a method for tranpose of text in a text file as below.
Text File:
abc
def
gh
--------
------
Its Transpose should display as below
adg
beh
cf
-------
-------
Given an array having 16000 unique integers, each lying within the range 1<x<20000, how do u sort it. U can load only 1000 numbers at a time in memory.
there are three shorted int Array
A1 : {2,4,9,16,19,68,78}
A2:{4,8,67,106,109,115,120}
A3:{9,15,19,108,119,130,190}
write an efficient algo to get the top 5 largest number from these three arrays.
Function would be like
int[] top5LargestNumber(int[] A1,int[] A2,int[] A3)
Merge sort is better for linked lists. How and implement ?
How we implement linked lists sorting with quick sort.
Note:- you can modify quick sort implementation.
How can design a TinyURL for a website? Design an algorithm and write sample code which generates TinyURL for a website.
Search for an element in a matrix. Rows and columns of the matrix are sorted in ascending order.
eg. matrix
[1 14 25 35]
[2 16 28 38]
[5 20 28 40]
[16 22 38 41]
search for 38.
The interviewer was looking for a solution better than O(n+m). He didn't want a solution which starts searching from the left bottom and go to right or above according to the key value to search. That solution has O(n+m) worst complexity, where n is row count and m is column count.write a code to find the equilibrium position of the array.
given an array: 3,-3,8,6,-1,-5
equilibrium position should be 2(element 8) sum of lower index(3+-3)=sum of higher index(6+(-1)+(-5))
Design an Class Structure for a Car
Given you an array of 100 Elements with one number missing, how will you find the missing number?
Array 1 to 100 with 55 missing.
write a O(n) based code to find the major element in an array.
array is 6,7,7,8,8,2,3,8,8,11,23,8,8,,3,3,4,4,4
output should be 8 because it is repeated max no. of times in the array.
C/C++
Maximum value Continuous Subsequence:
Given array A[n] find continuous subsequence a[i]..a[j] for which sum of elements in the subsequence is maximum.
Ex: {-2, 11, -4, 13, -5, -2} --> 11 - 4 +13 = 20
{1, -3, 4, -2, -1, 6} --> 4 -2 -1 +6 = 7
Time complexity should O(nlogn)
Given an in-order traversal of a special binary tree having property that the node is always greater than its left and right child. Construct the tree with minimal complexity.
Given a normal string S and regular expression string P find out whether P can be transformed into S or not?
for example:- P is "b*ba" and S is "bbba" now we have to return true as S can be obtained from P.
P.S:- Time complexity matters.
Let "output" denote the cut output by Karger's min cut algorithm on a given connected graph with n vertices, and let p=1/(n "up" 2). Which of the following statements are true? For hints on this question, you might want to watch the short optional video on "Counting Minimum Cuts".
For every graph G with n nodes and every min cut (A,B) of G,
Pr[out=(A,B)]≥p.
For every graph G with n nodes, there exists a min cut (A,B) such that
Pr[out=(A,B)]≤p.
For every graph G with n nodes and every min cut (A,B),
Pr[out=(A,B)]≤p.
There exists a graph G with n nodes and a min cut (A,B) of G such that
Pr[out=(A,B)]≤p.
For every graph G with n nodes, there exists a min cut (A,B) of G such that
Pr[out=(A,B)]≥p.
I need to store countries, its states and cities in a data structure.
The following queries might be used to fetch details
1) find list of states for a country.
2) find list of cities for a state.
3) find the name of the country and state for a city.
eg:
1) India -> Gujarat, UP, MP
MP -> bhopal,indore
Gujarat-> Surat,Ahmedabad, Baroda
2) USA -> Texas, California.. and so on.
Which is the best data structure that can be used to store these details.
there are five persons and each one of them hit a stump with a ball twice. Probability of each one hitting it is P then how many people hit the stump in both the chances?
calculate (x^y)%z without pow();
Implement enque() function for a fixed size circular queue with synchronization / locking using any atomic opetations.
Write a function which will find number of bits set and for each set bit its index. Function declaration will be: int find_set_bits(uint8 *from, int size)
Given 2 sorted linked list, merge them into a third sorted linked list
Reverse a string in place
Given any string (for e.g. "abfdRacecaRAbAorTITabcdef" find all the palindromes and return the longest one. Discuss the approach before you actually go ahead and code.
Given:You have given Amazon's stock prices for next 10 days
Find out: max benefit in best time complexity to buy and sell 1 share
Condition: Share must be sold any day after buying date.
For ex:
Share in thousands
5 1 4 6 7 8 4 3 7 9
Max benefit 9 - 1 = 8 thousand
You are having a 500 MB RAM and you have a program which uses malloc to allocate 600 MB memory . What will happen , will it be allocated using the concept of virtual memory or not , if yes how?
Which one you prefer and why?
Vector of pointer,reference and object. which one you will prefer.
you have given a post-fix of a binary try in which either you have 0 child(leaf node) or 2 child(internal node).
one more condition that all internal node are denoted via "i" and leaf node via "l".
we have to create this binary tree with this posfix.
Sort the letters in one word by the order they occur in another in linear time
Given two sorted arrays of equal length, how do you find a pair of numbers, one from each array, such that the absolute difference between the two numbers is minimum.
A tree, (NOT NECESSARILY BINARY), has nodes numbered 0 to N-1. An array has indices ranging from 0 to N-1. The indices denote the node ids and values denote the ids of parents. A value of -1 at some index k denotes that node with id k is the root. For ex:
3 3 3 -1 2
0 1 2 3 4In the above, nodes with ids 0, 1 & 2 have 3 as parent. 3 is the root as its parent = -1 and 2 is the parent of node id 4.
Given such an array, find the height of the tree.
In an N*M grid, in how many ways can you reach from top left (0,0) position to an arbitrary location (i,j) provided you can only move to the right or to the bottom in one step?
How do you compute the number of ways from (0,0) to (i,j) if there are arbitrary number of blocks on the way?
Arrange the following functions in increasing order of growth rate (with g(n) following f(n) in your list if and only if f(n)=O(g(n))).
a)22n
b)2n2
c)n2log(n)
d)n
e)n2n
Write your 5-letter answer, i.e., the sequence in lower case letters in the space provided. For example, if you feel that the answer is a->b->c->d->e (from smallest to largest), then type abcde in the space provided without any spaces before / after / in between the string. You can assume that all logarithms are base 2 (though it actually doesn't matter).
Given a matrix containing 0 and 1 only. WAP to find a square with all border as 1(not inside) also extend it for rectangle.
Given a function rand5() which generated random numbers from 0 to 5. Use this function to create rand7(). In deep approach was asked and further discussion was made regarding how to generalize it for creating m random no generator from n randon number generator. Plz give solution with proper explanation.
Write a high performance file search utility program . You are required to write a program that takes command line arguments and searches the required file in the current folder and the sub folders . Search could be for files or folders or both . Below are the four parameters that would be passed . You are also required to so proper exception handling and you code must be optimized as much as possible .
1) A top folder name : Folder from where search would begin. (Ex : C:/MyFolder )
2) Search Option (File /Folder /Both )
3) Search Pattern : A regular expression : (*my*.txt )
4) Timeout in seconds : once the operation treaches this timeout search should be stopped saying " Could not complete operation " and results obtained till then must be returned .
Need to write a efficient algo. how to find Max repeated word from a Given String for Example "How do you do" the result would be "2 times repeated word is "do""
k-way-Merge Sort. Suppose you are given k sorted arrays, each with n elements, and you want to combine them into a single array of kn elements. Consider the following approach. Using the merge subroutine taught in lecture, you merge the first 2 arrays, then merge the 3rd given array with this merged version of the first two arrays, then merge the 4th given array with the merged version of the first three arrays, and so on until you merge in the final (kth) input array. What is the running time taken by this successive merging algorithm, as a function of k and n? (Optional: can you think of a faster way to do the k-way merge procedure
?)
θ(nlog(k))
θ(nk2)
θ(n2k)
θ(nk)
Write data structure for query such as given user it returns all pages he visited with frequency.
If users clicks pages its (page) frequency count increases by 1.
Given an Array A[], find the maximum j - i such that A[j] > A[i].
For example Input { 34,8,10,3,2,80,30,33,1} and Output 6 (j=7, i=1)
Time Complexity should be less then O(n^2)
How can I find the shortest distance between the first and the last element in a two dimension Array of 0's and 1's.
Given if the element is 1 we can move left or down, if it is 0 we can only proceed downwar
Given one egg and a building with infinite number of floors. Find out minimum number of throws at which (least) floor egg will break, if thrown?
I said we have to start at floor 1 and keep incrementing and testing by moving 1 floor up. Then he said optimize it by minimizing no of throws. I could not find more optimal way. I told him that I know with problem with 2 eggs and finite floor building.
Then, he told me that now lets there are 2 eggs and infinite floor building, find minimum no if throws required to find least floor at which egg breaks.
I still could not do that for infinite floors.
Design a database schema for college elections and how will you make sure at database end that one user can vote for one person standing for one post only.
Design a database schema for college elections and how will you make sure at database end that one user can vote for one person standing for one post only.
Design a DVD renting library system
A prefix of a string S is any leading contiguous part of S. A suffix of the string S is any trailing contiguous part of S. For example, "c" and "cod" are prefixes, and "ty" and "ity" are suffixes of the string "codility". For simplicity, we require prefixes and suffixes to be non-empty and shorter than the whole string S.
A border of a string S is any string that is both a prefix and a suffix. For example, "cut" is a border of a string "cutletcut", and a string "barbararhubarb" has two borders: "b" and "barb".
We are looking for such borders of S that have at least three non-overlapping occurrences; that is, for some string that occurs as a prefix, as a suffix and elsewhere in between. For example, for S = "barbararhubarb", the only such string is "b".
In this problem we consider only strings that consist of lower-case English letters (a−z).
Write a function:
class Solution { public int solution(String S); }that, given a string S consisting of N characters, returns the length of its longest border that has at least three non-overlapping occurrences in the given string. If there is no such border in S, the function should return 0.
For example, given a string S as follows:
if S = "barbararhubarb" the function should return 1, as explained above;
if S = "ababab" the function should return 2, as "ab" and "abab" are both borders of S, but only "ab" has three non-overlapping occurrences;
if S = "baaab" the function should return 0, as its only border "b" occurs only twice.
Assume that:
N is an integer within the range [0..1,000,000];
string S consists only of lower-case letters (a−z).
Complexity:
expected worst-case time complexity is O(N);
expected worst-case space complexity is O(N) (not counting the storage required for input arguments).
Find the most common "3 page path" on a website given a large data log.
Find pairs of nums that add upto given number.
There are N(0 to N-1) players each having at Max 'M' (0 to M-1) number of followers. You have to select minimum number of players so that the total followers must be equal to a given number 'K'.
I/P would be like,
first line contain N, M, K followed by N lines containing string of 0 or 1 s.t. for i'th line if j'th char is 1 it means j'th person follows player 'i'
For. eg.
3 6 5
111100
000100
000010
ans=2 ( select 0th and 2nd )You are given a sorted array,increasing monotonically and decreasing in the same fashion.
WAP to find the index of an element in this array without calculating the pivot.
Running time should be O(log n).You can assume there ia no duplicate element in this array.
e.g: the array is {1,7,10,12,25,30,27,20)
input: arr[],key=27. output=6
input :arr[],key=0. output=-1
What is the best(time and space complexity) data structure to remove duplicates from given N elements.
And how?
Write a program to get shortest path between two given nodes in a binary tree.
find the path traversed by a KNIGHT to reach the destination from source in a 8x8 chess broad...
**you will be given the starting position and ending position ..
Given a list of numbers find the avg of last n numbers.
use data structure which will give best performance
Does HashMap allows null values as keys?
write a JAVA method that will count the number of duplicate words in a String, and will output the total count.
what data structure do you use?
Two 32-bit integers n and m are given and positions i,j,k,l are given.Write a method to copy the contents of m from position k to l into n from position i to j.
(example n=1010000000,m=10101010,i=3,j=5,k=5,l=7..output=10'101'00000)
There are some glasses with equal volume 1 litre. The glasses kept as follows
1
2 3
4 5 6
7 8 9 10You can put water to only top glass. If you put more than 1 litre water to 1st glass, water overflow and fill equally both 2nd and 3rd glass. Glass 5 will get water from both 2nd glass and 3rd glass and so on..
If you have X litre of water and you put that water in top glass, so tell me how much water contained by jth glass in ith row.
Example. If you will put 2 litre on top.
1st – 1 litre
2nd – 1/2 litre
3rd - 1/
Given a number x, less than 100. How will you generate true with probability x/100. So if x = 65, how will you generate true with probability 65/100. You can represent true by 1 and false by 0.
Develop an algorithm and write code to break a sentence without spaces into a sentence of valid words separated by spaces.
For ex: thissentenceisseparated needs to be broken into: this sentence is separated
Assume that you have a dictionary to check for valid words. Your algorithm should return false if the sentence cannot be separated into valid words.
Given n, how many structurally different binary trees can be formed?
For ex: n = 1 => one tree
n = 2 => two trees
O O
/ \
O O
n = 3 => five trees
O O O O O
/ \ \ / / \
O O O O O O
/ \ / \
O O O O
Given one integer n.
You have to find out for any integer n,How many distinguished n*n boolean matrix you can form such that each row and each column contains exactly.ceil(n/2) zeroes.
Follow Up: Write your code if you want to print the matrices as well
WAP to create a mirror of a binary tree. Extend the code or write a new code if not possible to do mirroring at alternate levels . Here in the second part , if the two trees are placed in front of each other , then odd levels should be exact mirror as a whole and even levels should be exactly same . Then write the iterative version for the above codes.
You are given an array of n integers which can contain integers from 1 to n only . Some elements can be repeated multiple times and some other elements can be absent from the array . Write a running code on paper which takes O(1) space apart from the input array and O(n) time to print which elements are not present in the array and the count of every element which is there in the array along with the element number .
NOTE: The array isn't necessarily sorted.
I had second round interview for amazon.inc ..and they asked me about fibonacci series code.as its simple enough i wrote the code
void fun(int n)
{
int a=0,b=1,c,count=0;
while(1){
printf("%d\n%d",a,b);
if(count==num)
{
break;
}
else
{
c=a+b;
a=b;
b=c;
count++;
printf("%d\n",c);
}
}
}and while writing this code i had written fib(n)=fib(n-1)+fib(n-2) so first they asked what is the complexity for the above code and i answered it as n as count==n it'll break and they told fine and looked at the fibonacci equation and asked whats the complexity for this? i answered its nlogn when considered fib() as the function as it'll be recursive ..
i want to know if the answer is correct and what is the better or best solution for fibonacci..
you have data provided to you in pairs. the relationship is that the 2nd element is a child of the first element.
print out the final output with tabs as shown in examples below
input: <a,b>
output: a
b
input: <a,b> <b,c> <d,c>
output: a
b
d
c
input: <a,b> <c,d>
output: a
c
b
d
For a technical phone screen:
Given a string "aaabbcccc", write a program to find the character with the second highest frequency.
consider a full tree.Every node at odd level has 3 children and every node at even level has 4 children. If root is at level one, derive number of nodes if the leaf nodes are at level k.
There is a bucket N which contains n nuts of different
sizes and bucket M of m bolts. Also there is a compare function which will take one bolt and a nut as input and return -1,0,1, respectively if nut size greater, equal, or lesser than bolt. Write an algorithm to find matching nits and bolts. Initially he gave sizes for nuts and bolts instead of compare function so i made use of hash map and solved it. So after that he gave this function and asked if there is a better soution than O(mn) ?
Write a method in your preferred language that given an array of n points on a plane specified by their (x,y) coordinates, and an angular size α, returns the direction β at which a beam of size α centered at the origin of the coordinate system would enclose the most number of points from the array. The direction of the beam can be represented by an angle β as shown in the illustration below.
Tip: The function arctan(y/x) returns the angle of a point.
In the illustration below, the blue dots represent points from the array and the grey beam represents the beam of size α pointed in a direction β where it happens to enclose three points.
algorithm which would display the numbers 10,09,08,....,1 and print welcome
algorithm to read sides of triangle and dertermine wheather it is isoceles or scaline
how to read number n and calculate 1+3+5+7+.....+n plz help
Write a program to print elements of a linked list in reverse order by using same single linked list in java.
Note : you can use only one linked list and no other data structure.
Given following design a data structure
Walker -> Walk and Breath
Talker -> Talk and Breath
Swimmer -> Swim, Talk, Walk and Breath.
Given a sorted array. Find the number of couples with the same difference. For example we can have an array with 2 couples whose difference is 3 and 4 couples whose difference is 5. The Output should be 2 & 4.
how to send message using php script ?
Construct a BST from inorder and preorder traversal string. Write code for it.
Given a tree, verify if it contains a subtree.
Given a maze that contains floor plan with rooms.
For example, consider a n*m matrix where each block represent a room.
You can move up-down and left-right from one room to another. But there are some rooms where there no door to one or more side of the wall.
some rooms are bathrooms.
Given a room location, return the nearest bathroom.
Start by writing method signature. Interviewer said that :)
It was bar raiser round.
Delete last node from the linked list. First node pointer is not given.
I told him its not possible in conventional linked list.
He asked me what if we can add some more data in node.
Data should not be a pointer to previous node i.e., it should still be singly linked list.
You are given a binary tree and a number k.
Print the sum of levels k^0, k^1, k^2, k^3..... untill all levels are exhausted.
Each K^ith level sum should be printed separately.
Given a sorted integer array and a number, find the start and end indexes of the number in the array.
Ex1: Array = {0,0,2,3,3,3,3,4,7,7,9} and Number = 3 --> Output = {3,6}
Ex2: Array = {0,0,2,3,3,3,3,4,7,7,9} and Number = 5 --> Output = {-1,-1}
Complexity should be less than O(n)
Design a air traffic control system
Find the longest substring that is the same in reverse.
As an example, if the input was "I like racecars that go fast"
the answer would be "racecar".
Test your code in the following String:
"FourscoreandsevenyearsagoourfaathersbroughtforthonthiscontainentanewnationconceivedinzLibertyanddedicatedtothepropositionthatallmenarecreatedequalNowweareengagedinagreahtcivilwartestingwhetherthatnaptionoranynartionsoconceivedandsodedicatedcanlongendureWeareqmetonagreatbattlefiemldoftzhatwarWehavecometodedicpateaportionofthatfieldasafinalrestingplaceforthosewhoheregavetheirlivesthatthatnationmightliveItisaltogetherfangandproperthatweshoulddothisButinalargersensewecannotdedicatewecannotconsecratewecannothallowthisgroundThebravelmenlivinganddeadwhostruggledherehaveconsecrateditfaraboveourpoorponwertoaddordetractTgheworldadswfilllittlenotlenorlongrememberwhatwesayherebutitcanneverforgetwhattheydidhereItisforusthelivingrathertobededicatedheretotheulnfinishedworkwhichtheywhofoughtherehavethusfarsonoblyadvancedItisratherforustobeherededicatedtothegreattdafskremainingbeforeusthatfromthesehonoreddeadwetakeincreaseddevotiontothatcauseforwhichtheygavethelastpfullmeasureofdevotionthatweherehighlyresolvethatthesedeadshallnothavediedinvainthatthisnationunsderGodshallhaveanewbirthoffreedomandthatgovernmentofthepeoplebythepeopleforthepeopleshallnotperishfromtheearth"given two arrays of same size, arrange the arrays such that a1*b1 + a2*b2 + .... + an*bn should ne minimum.
Design a online catalog system.
1. Catalog will have a list of Departments(sub-catalog) . Each department will have a list of products or sub-catalog.
2. Each product may have many Sub units(eg color price etc)
Eg :
Depart1 -> Groceries , Furniture
subment1 -> pen, pad
pen -> red & black
Also at anytime if we need to add discount that also should be possible.
If anyone come across can help me in this...
Design the juglee.com.
Write objects involved and their properties, behaviour and interactions.
Make valid and practical assumptions and design.
Please let me know your approach to this design questions.
Design a Dropbox invite system (refer other guys to join and get more space)
Assume whats required and design.
Given a bst and two nodes find out the maximum path between those two nodes
class Test
{
public void m1(String arg1){
arg1 = "Am I going to disappear?";
}
public static void main (String[] args)
{
Test test = new Test();
String iAmOfAnArgumentativeNature = "I am born new";
m1(iAmOfAnArgumentativeNature);
System.out.print(iAmOfAnArgumentativeNature);
}
}// end classWhat is the output?
Implement Object Pool for database connections in the following interface
interface Pool{
public Connection get()
public void put(Connection c)
}It should have object pool characteristics.
Hint - The emphasis is on which data structure you will use to achieve this.
If a java class has methods declared
as follows
class A
public synchronized void m1() {
//whatever code
}
public synchronized void m2 {
// whatever code
}
// note that return type is not relevant here.if a class is created with A a = new A() and
if a thread T1 is executing a.m1 and another thread T2 wants to execute a,m2 - what will happen?
A set of milk containers has capacities of 5, 4, 3, 2 , 1 etc . Lets say X containers
There is another set of Y containers
If you are going to transfer water from one to the other and each transfer has a fixed cost C, evaluate and state the complexity of the algorithm to achieve a least cost transfer.
Implement a stack that pops out the most frequently added item.
You have a huge set of stars as three dimensional coordinates. How would you find the k closest stars?
Find the shortest path between two nodes in a graph, given only the start node and the end node as parameters.
Write a function that given an array of integer and a number k returns true if there is 2 numbers which sum equals to k and false otherwise
You are given an external library (lets say a binary search library) which claims to have certain running time complexity. How would you verify that the claim of the rum time complexity is correct.
I told him give input of different length(1,N,N^2...) and see the differential change in running time. But he said in the shared system resources it wont give the good idea of running time.
Any other way we can do this?
How will you calculate the size of the object in java ? I gave answer for the serialized objects. The interviewer then modified the question that an ArrayList contains 10 non-serialized objects. How will you find out which object is the heaviest one ? He again added that the ArrayList is not a generic one, it may contain any kind of object like Organisation, Employee, Salary, PersonalDetails,OfficialDetails etc all object type. Now you have to find out which one is the heavy object through java program. He said there is some way you can measure the size of the object. Please help me.
In order to print all the nouns and verbs present in a given book, what is the underlying algorithm you see to achieve this problem? Discuss the pros and cons of your choice and also how would you test this method. You may assume that the system already knows what are nouns and verbs.
In a given array a = {1, 7, 3, 4, 5, 6, 2} Print the indices of all the combinations which lead to a given sum called target. For e.g. if the method is
Void PrintAllSumCombos(int[] arr, int target) - and the array shown above is passed with sum target = 7, then the output should be:
0, 3, 6
0, 5
1
2, 3
4, 6
Note: For simplicity, You may assume the array does not contain any negative numbers and also consider same set of indices with a different order as identical - for e.g. if 2, 3 is already printed, ignore 3, 2 as they are one and the same.
When i solved the knapsack problem using dynamic programming, he asked me why did I use dynamic programming rather than greedy approach to solve a knapsack problem?
Check if given binary tree is symmetric
Fastest String sorting algorithm?
Suppose you have file which has many strings. How will you sort all strings in that file. That file size is large.
Time complexity ?
Space complexity?
What is the difference between a tree and a map ?
You have 100 coins which needs to be distributed among 3 beggars A, B, C. In how many ways you can distribute these 100 coins to all the 3 beggars. Constraint: A cannot have more than 75 coins, B cannot have more than 50 coins, C cannot have more than 25 coins. Write complete code covering all the edge cases. Also suggest test cases.
Given a list of integers, find out the biggest interval that has all its members in the given list. e.g. given list 1, 7, 4, 6, 3, 10, 2 then answer would be [1, 4]. Develop algorithm and write code for this
Write code to clone a graph recursively
struct Node
{
int data;
vector<struct Node*> neighbors;
}Given function List friendList(Person p) which will give all freinds list of that person. Write a function such that printConnectedLeastFriends(Person A, Person B); if none of the friends found connected print "NONE";
What suggestions you can provide for improving the Page Rank algorithm.
Given a word consisting of letters, different words can be formed using all the letters in the word. Find the rank of input word in sorted list of all possible words.
Eg.
ABAB = 2
QUESTION = 24572
Program should use no more than 1GB memory and run within 500 milliseconds. Maximum input length = 25 and input word will contain atleast 2 different letters.
Name a data structure that can replicate a cache and why do you think so
Given - a number (n) and a sorted array
Find a number in the array having least difference with the given number (n).
Design a notification framework which notifies for birthdays, movie release, book release whenever one occurs.
Things kept on adding based on user subscription?
How all object, classes related/talk to each other?
There on, move on how to store them in tables?
Given a dictionary of words. You are given a word, return all anagrams of that word present in dictionary.
Given a Binary tree find out if it a BST or not?
Given a N * M matrix, you have to rotate it by 90 degree.
I gave him solution with transpose matrix & then reverse each row.
He was satisfied but after asked that this required each element to be touched twice. Can you do it like all elements will be touched once only.
Given a pointer to a node in tree, you have to find the depth of that node.
function signature:
int depth (root, node);
You given an array:
3, 2, 1, 6, 5, 4, 9, 8, 7
you have to find a 3 tuple which has property a < b < c, also a is before b, b is before c in array.
Answer can have multiple tuples, you have to find any one.
In this array, answer will be 3, 6, 9
Following sequence is given:
1,2,3,4,5,6,8,9,10,12,15,16,18,20,24
In this sequence, each number is multiple of 2,3 or 5 only.
This sequence does not contain 7 & 14 as these number has sequence 7 as multiple.
So, if you are given N find the Nth number of this sequence.
You are given a list of integers. You can call only one method on the list:getItemAt(x), which will return the integer at the index x from the list.
The list starts with value 0 and it goes on to have value 0 continuously until some index. After the index the list continues to have value 1 till the end.
You do not know the size of the list. Its huge. You need to find the index from where the value 1 begins in the list.
Given a string, compute the number of all possible palindromes of all the possible anagrams of that string.
String [] [] matrix = {{"A","N", "L", "Y", "S"},{"I", "S", "D", "E", "S"},{"I", "G", "N", "D", "E"}};
// 2. Given a word "DES"
// 3. Write a program to find the occurences of this word "DES". Letters must be next to each other in the matric.
// 4. "Next" means: left, right, up, down, left down, right down, upper left, upper right
// 5.. For example: S at (1,1): A, N, L, D, N, G, I, I are next to S at (1,1)
Required output
// // D - [1, 2], E - [1, 3], S- [1, 4]
// D - [1, 2], E - [1, 3], S- [0, 4]
// D - [2, 3], E - [2, 4], S - [1, 4]
// D - [2, 3], E - [1, 3], S - [0, 4]
// D - [2, 3], E - [1, 3], S - [1, 4]
The object of this exercise is to fix 3 known issue with the existing code, and add a new feature to the tool.
The known issues to address are:
· The current implementation of the tool incorrectly ignores white space (spaces and tabs) between words, which is a bug. Modify the code so that white space differences are correctly detected
· Tool doesn't report difference if second file is larger than first file
· For large input files the tool consumes considerable RAM. Modify tool to address this performance bug
The new feature to implement is:
· Add a new command line switch -i and functionality to allow case-insensitive comparison
Running the tool requires you to supply 2 command line arguments – these will be the paths to 2 text files that should be compared. You are responsible for creating this test data.
/*
* New Requirement:
* - Add a new command line switch -i and functionality to allow case-insensitive comparison.
*
* Issues to fix:
* - The current implementation of the tool incorrectly ignores white space (spaces and tabs) between words, which is a bug.
* Modify the code so that all white space differences are correctly detected and reported along with differences in words.
* - Tool doesn't report difference if second file is larger than first file.
* - For large input files the tool consumes considerable RAM. Modify tool to address this performance bug.
*
* Please ensure you include all test files that you create for each of your test cases along with your submission.
*/
namespace CsDiff
{
using System;
using System.Collections.Generic;
using System.IO;
class Program
{
static void Main(string[] args)
{
if (!ProcessArgs(args))
{
return;
}
using (FileReader sourceFile = new FileReader(args[0]))
using (FileReader targetFile = new FileReader(args[1]))
{
IEnumerator<string> sourceEnum = sourceFile.Words.GetEnumerator();
IEnumerator<string> targetEnum = targetFile.Words.GetEnumerator();
for (int word = 1; sourceEnum.MoveNext() && targetEnum.MoveNext(); word++)
{
if (sourceEnum.Current != targetEnum.Current)
{
Console.WriteLine("Difference at position {0}: '{1}' different to '{2}'",word,sourceEnum.Current, targetEnum.Current);
}
}
}
}
static bool ProcessArgs(string[] args)
{
if (args.Length != 2)
{
Console.WriteLine("Please specify [source] and [target] file paths");
return false;
}
for (int arg = 0; arg <= 1; arg++)
{
if (String.IsNullOrEmpty(args[arg]) || !File.Exists(args[arg]))
{
Console.WriteLine("File '{0}' not found", args[arg]);
return false;
}
}
return true;
}
}
public class FileReader : IDisposable
{
string[] words;
public FileReader(string path)
{
string fileData = File.ReadAllText(path);
words = fileData.Split(new char[] { ' ', '\t' });
}
public IEnumerable<string> Words
{
get
{
return this.words;
}
}
public void Dispose()
{
}
}
}
How can I store objects of differing types in a C++ container?
Given N integer array, I want to fill the array with product of all numbers except the number in that cell.
What is the complexity ? Do not worry about 0's or negative numbers in the array.
[Interviewer was more interested in how the multiplication/division gets effected as number of bits required to represent the intermediate products increases.]
Given a screen with all pixels having one of two colors. Now I will click on a random pixel.
Then that pixel & all the adjacent pixels with same color should change the color to the second color.
adjacent = vertically or horizontally above or blow.
Edit: Question seem to be not clear to some ppl. Giving an ex:
Given below & clicked on 2nd row, 2nd col
W B W W B W
B B W W B W
W B B B W B
W B W W B B
Covert to
W W W W B W
W W W W B W
W W W W W B
W W W W B B
How can we implement spell checker.
Write test case for testing wifi application. eg if user is connected to wifi using laptop, ipad,mobile device
Given an NxM (N rows and M columns) integer matrix with non-negative values (0..MAX_INT inclusive). What is the maximum sum from going top left (0, 0) to bottom right (N-1, M-1) ? The condition is that when you're at point (p, q), you can only move to either right (p, q+1) or down (p+1, q).
Expected time complexity O(N*M)
Expected space complexity O(N+M)
From the space complexity it looks like there is a DP solution, but I couldn't figure it out.
How can u prevent multiple threads from accessing getinstance() method of the singleton class. Wanted to add synchronization checks in it.
What do you mean by a 32 bit OS. Explain in details.
Code to find the Longest Increasing Subsequence of an array. Not the length but output the numbers.
Find two's compliment of a negative number. Code it.
Given a XML file with tags having millions of entry. Design a suitable algorithm for searching all the entries pertaining to a particular tag in the file. Stress was on optimization.
input: "kitten%20pic.jpg"
output: "kitten pic.jpg"
%20 -> ' '
%3A -> '?'
%3D -> ':'
modify your input in place.
no string library functions.
void DecodeURL(string str)
You are given 3 sorted array of equal length say 'm' and another empty array of length 3m. you have to put every elements from the three sorted array to the bigger array in minimum number of comparisons such that final array will have sorted numbers from all three array. eg. A[]={2,4,6,8} B[]={1,3,5,7} C[]={10,12,14,16} final output X[]={1,2,3,4,5,6,7,8,10,12,14,16}
You are given two eggs of same size and shape, there is a 50 stories building. you have to find the toughest egg in minimum number of attempts. Once egg is broken you won't be given a replacement.
Given the level order traversal of a complete binary tree in an array, how to store the inorder traversal of the said tree in the given array, without building up the tree.
Is there an in-place non-recursive O(n) solution for the said problem?
CALCULATE how many times a particular day occurs in a given year?
There is a clock at the bottom of the hill and a clock at the top of the hill. The clock at the bottom of the hill works fine but the clock at the top doesn’t. How will you synchronize the two clocks. Obviously, you can’t carry either of the clocks up or down the hill! And you have a horse to help you transport yourself. And, the time required for going up the hill is not equal to the time required to go down the hill.
if we open a new tab in a browser,is it a new process or thread?and what if we open a new window of the browser?
Imagine an alphabet of words. Example:
a ==> 1
b ==> 2
c ==> 3
.
z ==> 26
ab ==> 27
ac ==> 28
.
az ==> 51
bc ==> 52
and so on.
Such that the sequence of characters need to be in ascending order only (ab is valid but ba is not). Given any word print its index if valid and 0 if not.
Input Output
ab 27
ba 0
aez 441
Note: Brute-force is not allowed.
Given an array of numbers, arrange it such that all the numbers less than a given key should come before the key and all the numbers greater than the key should come after it.
For example: arr = { 0, -1, -2, 2, 0, 3, 5}, given key = 0
answer should be {-1, -2, 0, 0, 2, 3, 5}
Order of elements that are smaller or greater than key does not matter i.e. sorting is not expected. So, {-1,-2, 0, 0, 5, 2, 3} is also a correct answer.
Time complexity should not be more than O(n).
Input: Consider a file containing a list of 100,000 license plate numbers which follow the format ABC-123 and could be any value ranging from AAA-001 to ZZZ-999.
This data is expected to be read-in and stored in memory based on following requirements:
• The list can be reconstructed using the stored data. Original sequence does not need to be maintained.
• Perform searches efficiently on the stored data using the first 3 characters of the number as given below :
• List all licenses starting with ‘MMM’
• Count the total number license numbers starting with ABC
design a memory manager for a big chunk ok memory which allows multiple threads to allocate/deallocate memory concurrently.
Given a sentence and a word as arguments to a functions,
write a efficient algo for for finding the number of times the
word exists in the sentence...
* i gave hashmap solution but the interviewer was not impressed. asked for a better solution...
Given an array of ints, find the most frequent non-empty subarray in it. If there are more than one such sub-arrays return the longest one/s.
Note: Two subarrays are equal if they contain identical elements and elements are in the same order.
For example: if input = {4,5,6,8,3,1,4,5,6,3,1}
Result: {4,5,6}Implement T9 dictionary for mobile phone
find K Min Values in an array
find the indexes of Min Values in an array
find a Min Value in an array
A car is to be parked in 5x5 matrix parking lane.First of all we have to search the free space in the given matrix and then we have to allocate the memory to the car .Afterwards we have to remove the car from the parking lane.(In C)
In an array of unsorted integers (you may assume the array may contain +ve, -ve and 0s), write a function
int returnNthMax(int[] arr, int n)
which will return the nth Max number. For e.g. if this is given array {2, -4, 5, 6, 0, 7, -1, 10, 9} and n=1, it should return the max number, 10 and if n=3, it should return 3rd max number, which is: 7.
Difference between concurrency and parallelism
How has threading helped concurrency and parallelism?
Formula for nth PI is (-1^n)/(2n+1). Write an efficient way to calculate this.
After i wrote a recursive and iterative solution, she wanted a faster solution. So i went to threading.
Eventually she said that if the value of n is a million and you can't have million threads how will you distribute:
Problem is as n increases the above computation becomes time consuming and hence cannot be simply split in ranges.
She hinted me towards: Queue of jobs, threads picking jobs and en-queuing the work
Write a function to calculate the nth prime number:
N = 0; Prime#: 2
N=1; Prim#: 3
What is the complexity of this alogirthm
You are given a 2D array that is your sea. It has more than one ships which don't overlap each other. All ships are not necessarily of the same size.
You are to improve on performance and space is no concern.
Write a program that takes in two co-ordinates:
If the attack co-ordinates did not have a ship, print "Missed"
If the attack co-ordinates have a ship, print "Attacked Ship <Name>"
If the attack co-ordinates have a the same part of the attacked ship, print "Already Attacked"
If the last piece of the un-attacked ship was attacked print: "Ship sunk".
Given a binary tree with each node having a pointer to its parent, Write a function that can find the immediate right neighbor of a given node. Don't use BFS.
Node* RightNeighbor(Node* node)
Note: Root of the tree is not given
There is a file on a server. There are 3 access levels to this file: 1. Read\Write 2 Read 3. No access.
A person can: 1. Copy a file. 2. Edit it on the server 3. Overwrite the existing file on the server
Write all the test cases for this scenario
What could be performance hits for searching on Local computer i.e. if you are searching computer for content what are the parameters you will consider for performance
How will you design spotlight search feature in Mac OS
Differentiate between Google search and local computer search
Explain B trees and its applications
Which sorting algo you would like to implement as unix library and why?
1. Compare
-Heap sort Vs Quick sort - worst case, avg case and best case with applications
-Heap sort Vs Merge sort - worst case, applications
Don’t confuse heap sort with building min.max heaps
Design a tree, in which a node can have unlimited children and write a code to print each level in separate level.
(As the number of children is large we cant store them in queue.Can we do it without extra space ?)
Find the largest k elements from a large file?
You dont have RAM to store even k elements.
Algorithm to find square root of an algorithm
How to monitor health of the system?
What is a bad app and a good app?
Given an mxn matrix, design a function that will print out the contents of the matrix in spiral format.
Spiral format means for a 5x5 matrix given below:
[ 1 2 3 4 5 ]
[ 6 7 8 9 0 ]
[ 1 2 3 4 5 ]
[ 6 7 8 9 0 ]
[ 1 2 3 4 5 ]
path taken is:
[ > > > > > ]
[ > > > > v ]
[ ^ ^ > v v ]
[ ^ ^ < < v ]
[ < < < < < ]
where ">" is going right, "v" going down, "<" is going left, "^" is going up.The output is:
1 2 3 4 5 0 5 0 5 4 3 2 1 6 1 6 7 8 9 4 9 8 7 2 3Open two instances of Microsoft Word and print to printer simultaneously. How would the underlying printer driver work? How would you design the printer driver?
Given an array of positive integers, find the max no that can be formed by any permutation of the arrangement.
input {21,9,23}, output = 92321
Given a string dind the largest substring which is palindrome.
100 doors are closed , In first pass i open all of them , in 2nd pass i toggle every 2nd door , in 3rd pass i toggle every 3rd door , i continue it till 100th pass .. find all the doors that will remain open after 100 passes.
find the sum of all 4 digit numbers formed from 1 , 2, 3, 4 whithout rep .
given two unordered list find the greatest common integer
Find the largest binary search tree in a given binary tree
Define a class to represent a graph which supports following opertations
addEdge(Node n1,Node n2)
addNode(Object nodeData)
How do you differentiate between an edge n1->n2 and n2->n1
Given a string pattern of 0s, 1s, and ?s (wildcards), generate all 0-1 strings that match this pattern.
e.g. 1?00?101 -> [10000101, 10001101, 11000101, 11001101].
You can generate the strings in any order that suits you.
Given an array of strings, you need to find the longest running sequence of a character among all possible permutations of the strings in the array.
INPUT:
ab
ba
aac
OUTPUT:
a,3
Implement (in C++, MATLAB, or Java) a Fraction class that supports the following operations: addition, subtraction, multiplication, division, equality/non-equality, greater than/less than, and display. The program should take on the order of several hours. If there are techniques that would take longer to implement, note it down as comments.
Write a program to check if one tree is a subtree of other or not.
A binary search tree is given. Find the ceiling value present in the BST of a given key.
eg-
8
3 12
2 6 10 15
4key - 13 => 15
key - 4 =>6
key - 8 =>10
An array of size N is given. The array contains digits from 0 to 9. Generate the maximum number using the digits in the array such that it is divisible by 2, 3 and 5
input: {1,8,7,6,0}, output: 8160
input: {7,7,7,6,}, output : none(-1)
Two files containing large number, one in each. You have only fopen(), int read(fp), fclose(), fwrite(). Add these two numbers and write in third file with the help of given functions only.
Given a strictly sorted (increasing) array, find the elements whose value is equal to their index i.e. a[i] = i ?
The running time of the solution must be O(logn)
There is an infinite stream of numbers coming. you have to search for a particular number. How can you do it?
You are given a string1 and string 2. Check if the order of characters in string2 is same as string 1.
Program to rotate an array
Program to check if a tree is structurally similar
1. Question on evaluation of an expression
2. Question on Preprocessor directive #define
Design an algorithm to find all the nouns and verbs present in a book. Discuss and explain your decision as to why you chose that algorithm.
How many unique words(does not required to have meaning) can you generate from a "EFFICIENT" word
We toss a fair coin n times. A k-streak of flips is said to occur starting at toss i, if the outcome of all the k flips starting from i th flip is the same. For example, for the sequence HTTTHH, there is a 2-streak occurring at 2 nd toss, there is a 2-streak occurring at 3rd toss, and there is a 2-streak occurring at 5th toss. Here the total number of 2-streaks is 3 in the sequence HTTTHH. What is the expected number of k-streaks which you will see in n tosses of a fair coin ?
Write a simple Zoo simulator which contains 3 different types of animal: monkey, giraffe and elephant. The zoo should open with 5 of each type of animal.
Each animal has a health value held as a percentage (100% is completely healthy). Every animal starts at 100% health. This value should be a floating point value.
The application should act as a simulator, with time passing at the rate of 1 hour with each interation. Every hour that passes, a random value between 0 and 20 is to be generated for each animal. This value should be passed to the appropriate animal, whose health is then reduced by that percentage of their current health.
The user must be able to feed the animals in the zoo. When this happens, the zoo should generate three random values between 10 and 25; one for each type of animal. The health of the respective animals is to be increased by the specified percentage of their current health. Health should be capped at 100%.
When an Elephant has a health below 70% it cannot walk. If its health does not return above 70% once the subsequent hour has elapsed, it is pronounced dead.
When a Monkey has a health below 30%, or a Giraffe below 50%, it is pronounced dead straight away.
The user interface should show the current status of each Animal and contain two buttons, one to provoke an hour of time to pass and another to feed the zoo. The UI should update to reflect each change in state, and the current time at the zoo.
swap kth element from the beginning and kth element from the end of linked list.
print a decimal number in binary form. eg: number=10 or 2.22 or 0.876 ....
required to print only four number after decimal point
find all elements in the loop of an linked list....( linked list may or may not have loop)
Given a binary tree, for each node in the tree find the nodes with value greater than or equal to current node and sum them with the value of the current node. replace the node value with the above calculated sum....
given an array of number. find the largest possible sum of numbers in the array.
Condition: no two elements should be picked consecutively and position of elements in the array should not be changed..
given a binary tree in which a node can have two childs or no child. All the leaf nodes are represented as 'L' and parent nodes are represented as 'P'.
Given the preorder of the tree (string eg : PPPLLP....) find the depth of the tree.
Given a string T of length n, partition it in n' "phrases" (p1, p2, ..., pn'), such that
pi = pj + c, for some j<i, where + is string concatenation and c is a character
p0 = ''
p1 = pj + c where j < 1
T = p1 + p2 + ... + pn'
For example:
T = aababcabcd = a + ab + abc + abcd
p1 p2 p3 p4
There is a Blank Paper Sheet, Given a list of characters and their sizes,
for ex. A, P, O, N, Q with different font sizes and designs.
Now we need to cut characters from given sheet of paper of all sizes
atleast once. And also try to maxmize number of characters cut. Along with
this, when you remove a character, rest paper is more or less like a rough
sheet left. So we should try to minimize that rough sheet size as well.
Write Algo for this. Provide Data Structure, Complexity of algorithm.
Consider 3 32-bit (4 byte) numbers A, B and C
A: A3 A2 A1 A0
B: B3 B2 B1 B0
C: C3 C2 C1 C0
Modify C such that
C0=(A0+B0)/2
C1=(A1+B1)/2
C2=(A2+B2)/2
C3=(A3+B3)/2
Without using the obvious method of masking out each byte of A and corresponding byte of B, and add them, and then right-shifting once. Any other masking is allowed.
Given a number of N-digits A, I want to find the next least N-digit number B having the same sum of digits as A, if such a number exists. The original number A can start with a 0. For ex: A-> 111 then B-> 120, A->09999 B-> 18999, A->999 then B-> doesn't exist.
"Write test cases for reversing words of string ". For eg. "This is nice" is input string and output is "nice is This".
I gave him -
" "
"Hello"
"bye! Mr. X Y. Kumar"
But he didn't seem satisfied.
Can u plz tell what general guidelines should I follow for writing efficient test cases.
What more test cases should I have written for this question ?
How do you remove duplicates from an array of integers
Write down the fibonacci algorithm.
How do you remove repeated values from a Int Array returning the resultant array in the same order as the original.
What happens when you click on a link and get the web page? meaning what's the process behind that
for an array of integers find the first sequence in which the sum it's elements is equal to a given value and explain the complexity.
Take any array of integers and only copy the first occurrence of each value to another array. Explain the complexity of the algorithm.
Usage of a linked list, Differences with a vector. In which situations is better to use a vector or a list and why.
Given a list of n integers, find top k integers. What is time-complexity of your solution
Two arrays with integers. Find the values that are present in both of them. What is the time complexity?
How to do you ensure that there are no duplicates in the final output? --> time complexity. Can you get this done with O(n2)?
Design class structure for a building, floors and space. The space can be an apartment, a store or an office. Include any properties, fields and methods you think would be interesting to have.
Write a function to search for the existence of a string (target) in another string (str). The function takes two strings as the input and returns the index where the second string is found. If the target string cannot be found, then return -1
Write a function to check if two rectangles defined as below, have common area or not. The functions take the top left and bottom right coordinate as input and return 1 if they have common area, otherwise return 0.
[Question asked during online Test.]
Given a list of 'N' coins, their values being in an array A[], return the minimum number of coins required to sum to 'S' (you can use as many coins you want). If it's not possible to sum to 'S', return -1
Sample Test Cases:
Input :
Coin denominations: { 1,3,5 }
Required sum (S): 11
Output :
3
Giving a 2D (N*N) Matrix of characters, construct every possible words out of it. A cell in the matrix can only be used one time.
Construct ancesstor matrix of a given binary tree.
Find all the nodes at a distance 'k' from a given node. Should be k anywhere not just up and down.
Is it possible to compare two Binary trees for equality in iterative manner without using extra space?
Given a list of test results (each with a test date, Student ID, and the student’s Score), return the Final Score for each student. A student’s Final Score is calculated as the average of his/her 5 highest test scores. You can assume each student has at least 5 test scores.
You may use the JDK or the standard template library. The solution will be evaluated on correctness, runtime complexity (big-O), and adherence to coding best practices. A complete answer will include the following:
Document your assumptions
Explain your approach and how you intend to solve the problem
Provide code comments where applicable
Explain the big-O run time complexity of your solution. Justify your answer.
Identify any additional data structures you used and justify why you used them.
Only provide your best answer to each part of the question.
Use the following skeleton for your solutions.
Java:
class TestResult {
int studentId;
String testDate;
int testScore;
}
public class FinalScoreQuestion {
Map <Integer, Double> calculateFinalScores (List<TestResult> results) {
}Print the actual phone number when given an alphanumeric phone number. For e.g. an input of 1-800-COM-CAST should give output as 18002662278 (note: output also does not contain any special characters like "-").
Two tables. Country and City
country --> countryid, country name
city --> countryid, city name
1. how do you get the countries that has no cities?
2. how do you get the countries that has less than 3 cities and also make sure the countries with no cities also show up.
Design Elevator system. And then write an algorithm for that Design such that, the user request should be completed in logN time in a N story building with M elevators,
Given a server that has requests coming in. Design a data structure such that you can fetch the count of the number requests in the last second, minute and hour.
Given an 8x8 chess board, you have a bishop that moves from the current to the target position. write a code to find the minimum path from the current to the target position.
Design an API that will support constant time add, remove, search and random find operations. Random find will get a random number and return that element. Note: Only hash map will not be sufficient since it cannot support random read.
Given a family tree for a few generations for the entire population and two people write a routine that will find out if they are blood related. Siblings are blood related since they have the same parents. Cousins are blood related since one of their parents have the same parents etc. Design the data structure first and then write the routine.
Given multiple stream of input numbers each of which may not fit in memory (we can assume each source to be individually sorted) give an API design to merge and store a fully sorted array. Design must be object oriented which can handle any number of input source types. Obviously output also cannot fit in memory.
Given a sequence of numbers such that A[0] >= A[1] and A[N-1] >= A[N-2] find at-least one triplet such that A[n-1] >= A[n] <= A[n+1]. Better than linear time is expected.
Example: 9 8 5 4 3 2 6 7
Answer: 3 2 6
Find the majority number in a given sequence of numbers (a number that occurs more than N/2 times where N is the count of numbers in the sequence). Don't maintain a map of all occurring numbers along with a count. No number may be a majority.
Example: 1 1 2 3 4 1 6 1 7 1 1
Majority number is 1 since it occurs 6 times (> 11/2)
Given a file with a set of space separated numbers in a file write a program to remove duplicate rows. Two rows are duplicate if they contain the same numbers regardless of the order in which they occur. Constant time algorithm expected. LogN time is not good enough.
Given file:
1 2 3 4 5
3 6 7 8 9
2 4 7
1 5 3 2 4
Answer expected:
1 2 3 4 5
3 6 7 8 9
2 4 7
Given 7 letter tiles and a dictionary of valid words, return the set of words that can be generated using 1-7 of those tiles.
Example:
letter tiles: SAPAPER
word dictionary: A AA AAA APE PEA PARE PEAR FEAR SPARE APPEARS REAPPEARS
would return: A AA APE PEA PARE PEAR SPARE APPEARS
Is this even possible? Move the spaces to the starting of the string in a c style string. In place within one iteration.
Write a program to remove duplicates from array of prime numbers.
given two very big files , each having around 1 billion lines , u have to print all the lines that are common to both files . Please suggest a good optimal approach
Employees in my company are complaining about elevator, saying its too slow... Lift operates for 50 floors
I hire you and you have to tell me what is the problem and solutions to it.
Input:
Motor can't be changed
You can't get a new elevator as its too costly.
Get 5 matrices you would collect and how would you use them.
How would you design a movie search engine.
Think about both abstract and specific questions. How would you answer each of them.
ex: get me romantic movies, latest movies, movies with fight of no more than 10 mins.
How would you determine if ads clicks are coming through a human being or not (it could be a program, virus etc.)
Identify 5 parameters and how would you use each of them.
Once upon a time the following puzzle was suggested to pupils on a regional middle school olympiad on mathematics:
A set of coins consists of 15 coins: 14 coins are valid while a remaining 15-th coin is a false one. All valid coins have one and the same weight while the false coin has a different weight. One valid coin is marked. Is it possible to identify a false coin balancing coins 3 times at most?
A jury member was a trainer of a team of undergraduates for programming contests. So a question on how to put the puzzle for programming arose naturally. Fin ally the problem was formulated as follows:
A set of coins consists of N coins: (N - 1) coins are valid while a remaining N-th coin is a false one. All valid coins have one and the same weight while the false coin has a different weight. One valid coin is marked. Write a program which for every input pair
a number N of coins under question,
a limit K of balancing
outputs either ``POSSIBLE" or ``IMPOSSIBLE" with respect to existence of a strategy to identify the false coin balancing coins K times at most.
Input
The first line of input contains a single integer T that represents a total amount of different pairs (N, K) to process.
Output
The output file should contain T lines with ``POSSIBLE" or ``IMPOSSIBLE" per line.
Sample Input
3
6 2
10 2
15 3
Sample Output
POSSIBLE
IMPOSSIBLE
POSSIBLE
Given a set of numbers, find the longest subset with consecutive numbers be it any order.
Input:
S = { 5, 1, 9, 3, 8, 20, 4, 10, 2, 11, 3}
we have 2 consecutive sets
s1 = {1, 2, 3, 4, 5}
s2 = { 8, 9, 10, 11}
Ans.
s1 = {1, 2, 3, 4, 5}
how to solve this ((3000000!)/(30!)^100000)%(any prime no.) in C++
Check if the given binary tree is BST or not.
Given an integer array, find pairs in an array which sum up to a given number.
For example: Array{4,5,1,3,2} and required sum=6 then output should be [1,5] and [2,4].
N nodes, each node consists of a couple fields and methods. These are:
int id; //every node has an ID. All of these IDs are sequential, and begin with 0. I.e. all ids are uniquely in the range of 0 t N-1
int val; //every node has a value
int max; //max = N. Every node knows how many nodes are in the system.
void send(int idTo, int payload)
int recv(int idFrom)
Write a single piece of code which runs on every node simultaneously, such that when it is finished running every node in the system knows the sum of the values of all the nodes in the system.
Given two array of integers write two functions that will return an Union and Intersection
Time efficient
Both time and space efficient implemented
Write a writer thread and a Reader that share a fixed-size buffer and an index to access the buffer .The writer should place numbers into the buffer while the Reader thread should remove the numbers.The order in which the numbers are added or removed is not important.
find all set of elements in an array with sum equal to k(given)
Write a program to find whether a given number is a perfect square or not. You can only use addition and subtraction operation to find a solution with min. complexity.
i/p : 25
o/p : True
i/p : 44
o/p: False
Design a fixed size LRU cache that offers inserts into and retrievals from the cache in constant time.
Suppose you have an array of +ve numbers, -ve numbers and zeroes. Devise an algorithm to find the maximum contiguous subsequence product.
For 7 -3 -1 2 -40 0 3 6, the max subsequence product = -1 * 2 * -40 = 80
For -3 7 2 0 -5 7 -2 -2 2, the maximum subsequence product = -5 * 7 * -2 = 70
How to read a large file efficiently in java
Given an unsorted array (of unknown length .. can be infinite even ).. at any point of time , how to find a number which is repeated for maximum times , followed questions is how to find a number which is repeated for n times.
Answer I proposed is using combination of binary st as ell as heap.
ex: this binary search tree will have structure which even has pointer to its correponding healelement's pointer.
while inserting an element into tree , will check whether it is repeated , if yes , will increase the priority of this element , and adjust heap accordingly.
Please comment on this solution
Write a calculator program in Java that evaluates expressions in a very simple integer expression language. The program takes an input on the command line, computes the result, and prints it to the console. For example:
% java calculator.Main “mult(2, 2)”
4
Few more examples:
Input Output
add(1, 2) 3
add(1, mult(2, 3)) 7
mult(add(2, 2), div(9, 3)) 12
let(a, 5, add(a, a)) 10
let(a, 5, let(b, mult(a, 10), add(b, a))) 55
let(a, let(b, 10, add(b, b)), let(b, 20, add(a, b)) 40
A “let” operator for assigning values to variables:
let(<variable name>, <value expression>, <expression where variable is used>)
This was the question of two buckets of 3 and 5 litres each. Now measure four litre. I had given 2 solutions but still he wanted 3 solution.
1st soln: fill 3 litre and then interchange in various ways to get 4 litre.
2nd soln: fill 5 litre and then interchange in various ways.
do you have any soln other than this.
Pattern Matching
----------------
Characters: a to z
Operators: * +
* -> matches zero or more (of the character that occurs previous to this operator)
+ -> matches one or more (of the character that occurs previous to this operator)
Output if a given pattern matches a string.
Example:
pattern:a*b
string:aaab b, ab, aab, aaab, ab
output:1
pattern:a+aabc
string:ab aabc, aaabc, aaaabc ..
output:0
pattern:aa*b*ab+
string:aab aab, aabab, aaaabbab
output:1
pattern: a+a*b*
string: a ab, aab, aaabb
output: 1
Valid Assumptions: Please assume that both the pattern and string input are valid
Given an array of integers. Find two disjoint contiguous sub-arrays such that the absolute difference between the sum of two sub-array is maximum.
* The sub-arrays should not overlap.
eg- [2 -1 -2 1 -4 2 8] ans - (-1 -2 1 -4) (2 8), diff = 16
I gave him o(n^2) algorithm but he was not satisfied.
implement a method to print the transpose of a text file.
example if the text is
=====
abc
def
gh
====
the method should print
====
adg
beh
cf
=====
In a certain language which has same alphabets as in english language (ie. a-z), but the order of the alphabets is different (for eg 's' is the first character, 'g' is second, and likewise). Given a dictionary of this new language (which has words arranged according to new alphabetical order), FInd out the order of alphabets in this language.
There is a server when a user can login.
A used can login multiple times.
you have to return number of unique users in last 10 minutes.
Retrieve unique user count operation should be as fast as possible.
Note:
A user who has done login in last 10 minutes more than once should be counted only 1.
It is possible that in a particular duration no user has logged in.
Given a binary tree.
Print nodes of extreme corners of each level but in alternate order.
10
5 11
9 20 - 15
14 - - - 25
30then output should be 10,11,9,25,30
left most of 0th level
right most of 1st level
left most of 2nd level
& like this
Write a program to reverse a sentence in a zigzag order.
i/p: I am a software programmer
o/p: programmer erawtfos a ma I
Find the first non repeating character in a given string. You may assume that the string contains any character from any language in the world, for e.g. an Arabic
or Greek character even.
Given life time of different animals. Find period when maximum number of animals lived. ex [5, 11], [6, 18], [2, 5],[3,12] etc. year in which max no animals exists.
How would you test the search functionality on Bing?
Give you two sequences of length N, how to find the max window of matching
patterns. The patterns can be mutated.
For example, seq1 = “ABCDEFG”, seq2 = “DBCAPFG”, then the max window is 4. (
ABCD from seq1 and DBCA from seq2).
You are given a file (and you do not know how big the file is, nor how big the lines in the file are). Write an algorithm that will generate a random number (which will be used to index into the file) such that the output of lines will be roughly proportional? That is if the file contained 4 lines, and if I ran the program 1 million times I should get each line printed approximately 250K times.
write a sample code to find no of 'a' words in a sentence?
Eg: If a sentence is given as "I found an apple in a tree."
The output is : 1 (not 2)
We have to count no of words.
d1 = a1*x1 + b1*x2 + c1*x3
d2 = a2*x1 + b2*x2 + c2*x3
d3 = a3*x1 + b3*x2 + c3*x3
Knowing all of a,b,c,d, find x1, x2, x3. As you might notice, this is high school math. But it's hard to write the code for solving it.
/*
/a1 b1 c1| /x1| /d1|
|a2 b2 c2|*|x2|=|d2|
|a3 b3 c3/ |x3/ |d3|
*/
double A[3][3], X[3], D[3];
X[0] = ?
X[1] = ?
X[2] = ?
If a=1, b=2, c=3,....z=26. Given a string, find all possible codes that string can generate. Give a count as well as print the strings.
For example:
Input: "1123". You need to general all valid alphabet codes from this string.
Output List
aabc //a = 1, a = 1, b = 2, c = 3
kbc // since k is 11, b = 2, c= 3
alc // a = 1, l = 12, c = 3
aaw // a= 1, a =1, w= 23
kw // k = 11, w = 23
Given:
Array of n objects of type Object
///<summary>
/// Given two objects, this function returns a value between 0-100 depending on the relation of the two objects
/// <param1: objToBeCompared>Any object instance which has to be compared to the objReference</param1: objToBeCompared>
/// <param2: objReference>Instance of an object against which the other instance of the Object is to be compared</param2: objReference>
/// <return>A value between 0-100</return>
///</summary>
int Compare(Object objToBeCompared, Object objReference)
Now implement a function:
///<summary>
/// Given an object array of length n, a reference object this function returns the top numberOfMatches matches based on Compare(obj, obj) function's return value
/// Start with the object(s) that return 99 and go up till you find numberOfMatches element
/// The return array doesn't have to be sorted by the Compare value
/// <param1: objects>Array of n Object from which numberOfMatches have to be selected</param1: objects >
/// <param2: ObjectToBeCompared>Object against which the other objects need to be compared to</param2: ObjectToBeCompared>
/// <param3: numberOfMatches>number of matches to be returned</param3: numberOfMatches>
/// <return>Array of numberOfMatches objects</return>
///</summary>
Object[] FindTopMatch(Object[] objects, Object ObjectToBeCompared, int numberOfMatches)
You have two threads one printing even numbers in order and other odd numbers. Design an algorithm so that it prints numbers in natural order
1. Which of the following regular expressions denotes zero or more instances of an a or b?
a) a l b
b) (ab)*
c) (a l b)*
d) a* l b
Given a 2D rectangular matrix of boolean values, write a function which returns whether or not the matrix is the same when rotated 180 degrees.
Write a MapReduce job that takes in two text files, and output the probability that those two files are identical (with 0% -> completely different, 100% -> completely different).
Clarification: Matching should not be a per-line diff, but it's about the content. One article could be 80 characters per line in one version, but could be 100 characters per line in another version, for the same content. In that case, it should be 100% match even though, if you are comparing line by line, they are totally different.
Given a matrix consisting of nos you can print the max length of sequence possible where in a sequence each consecutive nos have a diff of +1 or -1.
Ex :
3 5 7 3
4 5 8 1
6 4 5 2
here sequence is
3
4 5
4 5
What are checked exceptions
Given +ve numbers in an array . Put the even #s to the left of the array and the odd to the right side of the array . Don't use extra array.
code a singleton class
Rakesh likes skiing a lot. That's not very surprising, since skiing is really great. The problem with skiing is one have to slide downwards to gain speed. Also when reached the bottom most point one has to wait for ski-lift to get to higher altitude.
Rakesh seeks your help to know the longest run possible with the given peaks. That altitude of different peaks is given by a grid of numbers. Look at this example:
7 2 3 4 5
36 37 38 34 6
33 44 46 40 7
24 43 42 41 8
35 32 47 30 9
One can ski down from one peak to a connected peak if and only if the height decreases. One peak is connected to another if it's at left, at right, above or below it. In the sample map, a possible ski path would be 36-33-24(start at 36, end at 24). Of course if one would ski 46-44-43-42-41-30-9....3-2, it would be a much longer run. In fact, it's the longest possible. There could be more than one longest ski path, but all Rakesh needs from you is to tell maximum number of peaks he could cover for a given map, in this case it is 14.
Input ::
All input comes from input.txt file. The first line contains the number of test cases N. Each test case starts with a line containing the name (it's a single string), the number of rows R and the number of columns C. After that follow R lines with C numbers each, defining the heights. R and C won't be bigger than 100.
Output ::
For each test case, print a line to output.txt containing the name of the area, a colon, a space and the length of the longest run (maximum points covered) one can slide down in that area.
Sample Input
2
Manali 10 5
56 14 51 58 88
26 94 24 39 41
24 16 8 51 51
76 72 77 43 10
38 50 59 84 81
5 23 37 71 77
96 10 93 53 82
94 15 96 69 9
74 0 62 38 96
37 54 55 82 38
Narkanda 5 5
1 2 3 4 5
16 17 18 19 6
15 24 25 20 7
14 23 22 21 8
13 12 11 10 9
Sample Output
Manali: 7
Narkanda: 25
Consider an array of integers wherein each element is +1 or -1 its preceding element. Given a number, find the first occurence of this number (index) in this array without using linear search.
For example, consider the array :
4 5 6 5 6 7 8 9 10 9 10 (each element in this array is +1 or -1 its preceding element)
Input : 10 (find first occurence of 10 without using linear search)
Output : 8
Given a 'friendship' graph, how would you generate friend suggestions for people, and how would you distribute the data across machines?
Find out the no of times the statement will get executed for the below code snippet.
int temp = 1;
for(int i =0; i <n; i++) {
for(int j = 0; j<= i; j++) {
for(int k= 0; k <= j; k++) {
temp++;
}
}
}
System.out.prinln(temp); // Or what will be the value of the temp?.
Find the no classes, no methods and the no class level variables from a given Java file...
Example :
Input: test.java
Output:
Number of class in Java file. : Class names
Number of Methods in Each class : count of methods for each class
Number of Class variables : Count of variables for each class.
How to find in a binary tree, whether all leaves are at same level or not, and return a boolean value after identifying this.
Given a binary tree, a complete path is defined as a path from root to a leaf. The sum of all nodes on that path is defined as the sum of that path. Given a number K, you have to remove (prune the tree) nodes from the tree which lie on a path having sum less than K.
Note: A node can be part of multiple paths. So we have to delete it only in case when all paths from it have sum less than K.
Design an online marketplace.
Given 2 arrays.Imagine you are making bst from each array.u need to tell whether 2 bsts will be identical or not without actually constructing the tree.
Ex:
2 3 1
2 1 3
will construct the same tree
A1[]={2,1,3}
2
1 3
A2[]={2,3,1}
2
1 3
WAP to send mails(or any other functionality can just write a dummy method call) simultaneously using multiple theads. (Use of ExecutorService not allowed).
How will you find a loop in a linked list. e.g. if the 4th node of the list is pointing back to the 2nd node (for a list of size 6), then it will be in a loop; how will you find this node?
Write code to Print the power set of given string
Bar raiser round
Write code to return Kth smallest node from BST
Find a pair of numbers from Array that will sum up to K
me : I know this , told him both approaches using sorting as well as HashTable
Write a Program for Dictionary which has functionality of lookup and insert . This program should be able to add words on the fly
I wrote simple code using HashTable
follow up
1) Now we are getting too many words what happens
me: Hashtable will dynamically resize resulting into performance hit . Also they might get hashed to same location as well as we might run out of main memory
2) Okay you are out of main memory , How will you scale this program
me: I will create buckets of HashTable lets say 26 buckets for one for each alphabet and would put them on different machines
3) Lets say you are out of memory on those machines too
me: Okay I need to put them on secondary storage . Here we can have fileSystem or Database . I chose database . I will create simple DB schema of BucketNumber and word .
I will use buckets on main memory as cache , if we are not able to find a word in the bucket then query databse with bucket number and words then remove the least number times looked up word (every time we lookup a word we increament the count i.e value in key,value pair on hashtable) from that bucket and add this word .
I mentioned that bottleneck in this case will be every time a word is not present we need to query DB which usually has high latency which will result into performance hit
4) Lets say we are okay with latency but what if we are getting inserting words between that are only between only in two buckets ex. words starting from a and b only
Given following interface
Class NumberPool
{
int CheckOut()
void Checkin(long long number)
}Write functionality for Number pool which has numbers from 0 to long long
Where checkout returns the next smallest available number from the pool and Checking accepts the number returned by user and adds back to pool .
You are given two arrays find if they are equal
I gave solution using Hash table and he was fine with it
Given two sorted arrays, find the median of each array. The length of the arrays are m and n and we should not use extra buffer. We should find the median and time complexity should be less than 0(M+N);
assume that n is power of 2 solve recurrence relation t(n)=2(t/2)+2 if t(2)=1,t(1)=0
Print the sum of all nodes of a binary tree, excluding leaf node values.
From a binary tree the leaf nodes are removed to get another tree and then leaf nodes are removed from that tree also. The process is continued till all the nodes of the tree are removed.
Given a set of inputs where each line contains the leaf nodes removed in a iteration. Print the pre-order traversal of the binary tree.
For example:
BDHPY
CM
GQ
K
Output would be:
KGCBDHQMPY
You are given two sorted arrays of size n and n+m respectively. Merge these two sorted arrays without using a third array and the resultant array must be sorted ?
For eg.
arr1 (size 3): {1, 4, 6}
arr2 (size 8): {2, 3, 5, 7, 8, null, null, null}
Result must be in arr2 as :
arr2 (size 8): {1, 2, 3, 4, 5, 6, 7}
This question was asked in todays interview's written test. According to me it should go into infinite waiting, but when I run this code on my computer, it safely ends up printing the value. I executed n number of times but still it finishes without without going into infinite waiting.
Can someone explain.
static class Job extends Thread {
private int counter;
@Override
public void run() {
synchronized(this) {
for(int i = 0; i < 100000; i++)
counter++;
this.notifyAll();
}
}
}
public static void main(String[] args) throws InterruptedException {
Job job = new Job();
job.start();
synchronized(job) {
job.wait();
}
System.out.println(job.counter);
}Let A = A[1], . . . , A[n] be an array of n positive integers. Let s = A[1] + · · · + A[n] be the sum of all the numbers in the array. For 1 ≤ i ≤ n, let S(i) = s − A[i].
Design a linear time algorithm (O(n)) to compute S[1], . . . , S[n] only with plus operations (you are not allowed to use the minus operation)
Merge the given 2 input sorted arrays of numbers into one . The merged array stays sorted .
How will you detect a loop in linked list.
Follow up question: why fast pointer always twice faster than slow pointer. Why not three or more times faster.
A stirng is represented using a linked list how will you find if it the string is palindrom.
There is an server which has infinite number of services s1, s2, s3,....Also there is a priority attached to it. There is one to one mapping between the services and priorities. The following mapping is stored by the server.
p1 --> S1
p2 --> s2
p3 --> s3
p4 --> s4
p5 --> s5
p6 --> s6
.
.
.
infinite
Whenever a user logs in to the system, it assigns a service with lowest priority available to it.
Whenever a user logs out of the system, service is returned to the pool of free services.
a. What is the datastructure that you will use to store these services. You dont have to store the mapping. Mapping is already stored in the system.
b. Can you write the code for it.
c. How will you go about writing automation framework to test it
Please let me know if anyone need any more info about the question
Design the below scenario in Java.
In an Olympic event there is a running track and it is used for 100m,200m,400m. You have 10 participants.
When the event start , capture the time taken by each participants. Determine who is the winner in each event.
Design the below scenario in Java.
You have to maintain the family tree of 10 generation. For a family you have to store father, mother and their children.
You have do the following operation.
When you search by a particular name of father/children, It will print whole 10 generation.
Calculate the time and space efficiency of your search operation.
There are N floors and N persons each one is tagged with some random unique number between 1 to N(represents floor number).
We have a lift which can accommodate one person at a time. Every person is in some random floor.
Initially lift is at floor 1 and all floors have single person. Problem here is.. we have to move the persons to their corresponding floor with minimum travelled distance of lift.
Restriction : Lift can have at most one person at a time.
One more thing we have to think of is .. At a time, we can keep more than one person in a floor.. means, we don't necessarily need to take the person out from the floor if we keep another person on the same floor.
Q1. Given two arrays of size n1, n2, sum up the two arrays in such away that the resultant array is computed in the below way.
arr1 : {a1,a2,a3}
arr2 : {b1,b2,b3,b4}
resultant array : {a1+b1, a1+b2, a1+b3. a1+b4, a2+b1, a2+b2, a2+b3, a2+b4, a3+b1, a3+b2, a3+b3, a3+b4}
find the median of the resultant array in n1 + n2 time .
By default, Hashtable is unordered. Then, how can you retrieve Hashtable elements in the same order as they are put inside???
how can we measure size of a object in java?
How the java calculate the size for Hashset and what would b the output. Jsutify your answer with Java point of view..
import java.util.HashSet;
public class HashTest {
private String str;
public HashTest(String str) {
this.str = str;
}
@Override
public String toString() {
return str;
}
@Override
public int hashCode() {
return this.str.hashCode();
}
public static void main(String args[]) {
HashTest h1 = new HashTest("1");
HashTest h2 = new HashTest("1");
String s1 = new String("2");
String s2 = new String("2");
HashSet<Object> hs = new HashSet<Object>();
hs.add(h1);
hs.add(h2);
hs.add(s1);
hs.add(s2);
System.out.print(hs.size());
}
}
Design a counter across all Google's servers.
need to implement a weather report functionality. user will provide the city name , need to return the weather report.
if weather station exists n functioning properly , will return the weather report of that station .
else ,
will return the nearest available weather station report.
interviewer looking for optimized manner.
looking for datastructures to stores the cities n algo to return the report.
Write a Method in Java which takes an Array of strings and from the array of strings returns only those strings which have a consecutive repetition of a particular letter for eg: if I/P is {"Dauresselam", "slab", "fuss", "boolean", "clap"}
then O/P should be {"Dauresselam", "fuss", "boolean"}
If a linkedlist is having loop, how to find the last node of the loop .
A large character array is there in which there are spaces in between the character like ab c d ...etc
Write a method to search any character in the above array in O(n).
Given a 2d matrix with characters and a dictionary. Find all the valid words in the 2d matrix. The words can be towards right, left , up or down. Exact code to be given.
You are given a doubly linked list and an array of references to nodes on the linked list. How many "blocks" are there present in the linked list?
A "block" is defined as a group of nodes on the list with references directed at them and adjacent to eachother.
For example
[node #0] -><-[node#1] -><-[node#2] -><-[node#3]
node[] nodes = {ref_to_node#0, ref_to_node#2, ref_to_node#3};
Is two blocks because the first block is at node #0.
Node #1 has no incomming reference. Node #2 and Node #3 have references are are adjacent so it's just one block.
Implement using JAVA: Hint: You can try using a HashMap.
Thanks.
Given a sorted array, write a function to search first occurrence of a number in the array. If not found return -1.
Example::
{2,2,2,3,4,5,5,6,6,8,9}
search 6
should return 7.
For a given BST, connect each of its right child to its inorder successor.
There is a binary tree of size N. All nodes are numbered between 1-N(inclusive). There is a N*N integer matrix Arr[N][N], all elements are initialized to zero. So for all the nodes A and B, put Arr[A][B] = 1 if A is an ancestor of B (NOT just the immediate ancestor).
Given a file of n lines, where n-1 lines are identical and 1 line is different. Find the unique line in not more than one scan of the file.
There are exactly N advertising boards on the highway. Now a company want to advertise on some of these advertising boards (each advertising board costs some money).
Company strategy is that, they want at least 'K' advertisement should be there among M consecutive advertising boards. But at the same time Company want to pay minimum for its advertisement.
Now, what is the total number of ways Company can advertise meeting its minimum cost strategy.
Also 1 <= K <= M <= 50 and M <= N <= 10^9
As for Example: N = 3, M = 2, K = 1 ==> there is only one way for minimum cost, ie. 0C0 , where '0' denotes No company advertisement, and 'C' denotes company advertisement board.
Similarly, for N = 4, M = 2, K = 1 ==> there are 3 possible ways, ie. C0C0, 0C0C, 0CC0.
Problem: you are given 2 words with equal number of characters. Find an algorithm to go from first word to second word, changing one character at each step, in such a way that each intermediate word exist in a given dictionary.
Example:
Words are pit, map. A possible solution:
pit, pot, pet, met, mat, map
How would you test each of the 3 layers in a 3-tier web app?
How would you test amazon search functionality on the home page?
Give me real time application of BST.....
You are given an array of 1's 2's and 3's. Sort this list so the 1's are first, the 2's come second, and the 3's come third.
Ex: Input [1, 3, 3, 2, 1]
Output [1, 1, 2, 3, 3]
But there is a catch!! The algorithm must be one pass, which means no merge/quick sort. Also no extra list allocations are allowed, which means no bucket/radix/counting sorts.
You are only permitted to swap elements.
If you are going to debug a program with about 5000 lines of codes (written in C), given that some of its features are working fine while other are not, how are you going to fix it?
Given an array with different numbers and a number of C,so how to find all the combinations which the sum is C..like..array={1,2,3,4},C=3,,return is 2,which contains two combinations{{1,2},{3}}.
You visit a website and it is slow today (it is not slow everyday). What could be the cause(s) of the slowness?
which data structure should be used to implement thread pool ? How to assign particular thread from thread pool ?
Given a list of n points in 2D space. Lets call them (X1,Y1), (X2,Y2) .... (Xn,Yn). Find the optimal way to retrieve the result of following query.
SELECT min(X) FROM (2D Points) WHERE Y between Ymin and Ymax.
Suppose there is a directory XYZ having too many files (100 to 10000). Each file contain the format like first line having company name and second line some data values. We need to read each files in directory and create the new directories at some path with company names and move that file (1.txt ) to that directory.
what should be design.
My suggestion was to Create a function ScanDir() which will read the count of files and will make loop to read the file and will create a thread for that file and move to next file and process the all files.
Two numbers are missing from the first hundred numbers. They are NOT sorted. How to find them?
You can't sort.. and can't iterate one by one.. has to be less than O(N)? Can't use stack , set or any collection interface or in fact any other data structure or array!
An array contains N numbers where N is huge. There are only k distinct numbers. Sort those k numbers.
I tld him to use a hashmap for this. He was fine with the solution. But he wanted me to optimise it for a multicore machine. I couldn't come up with an answer. :(
You are given a long list of integers, so long that you can not fit the entire list into memory, implement an algorithm to get the max 100 elements in the list.
Given these 4 commands :
INCREMENT:
READ V
WRITE V + 1
ZERO
WRITE 0
ASSIGN : =
LOOP : FOR <integer> = <start> to <finish> do
...
END FORDefine these 4 functions: Decrement, Divide, test If equal (pseudo code).
You have an array of binary numbers as "00001101000001010100000..."... We need to find the First occurrence of 1 in this series.. using binary search.
we need to design an algorithm of complexity less than O(n).. and we need to use binary search strictly..
Using these 3 functions:
INCREMENT:
READ N1
WRITE N1 + 1
MINUS:
READ N1, N2
WRITE N1 - N2
MULTIPLY:
READ N1,N2
WRITE N1*N2Define these four functions: Greater than, Equality, Nonequality, Divide.
How can you implement multiplication operator using increment operator (No arithmetic operation is allowed)?
Write a function to evaluate a string that has only integers, and operators '+' & '*'. The evaluation should be done in a single pass. For example passing "3*2+5*6" should result in this function returning 36.
Write a function fix a loop in the linked list based on the assumption that the linked list is sorted.
How would you find if a linked list has a loop? How would you do it without using additional memory, if the linked list is sorted.
Write a function to find a key in Hash map if the value associated to that key is given as input. As a followup, swap key & value assuming that value is not equal to any of the existing keys.
Write a function to perform string replace without using any inbuilt functions.
// Given two lists of strings build a new list that has all strings that appear in both the original lists. If the same string appears more than once output it as many times as it appears in both lists
//
// Example:
// "dog", "bird", "elephant", "dog", "dog", "cat"
// "cat", "dog", "dog", "cat", "cat", "fish"
// Result (order doesn't matter)
// "dog", "dog", "cat"
//Given an array of NxN, print its diagonals from top-right to bottom-left.
//Sample Input:
// [[1, 2, 3],
// [4, 5, 6],
// [7, 8, 9]]
//Sample Output:
//1,
//2, 4,
//3, 5, 7,
//6, 8,
//9
Given an array of values, design and code an algorithm that returns whether there are two duplicates within k indices of each other? k indices and within plus or minus l (value) of each other? Do all, even the latter, in O(n) running time and O(k) space.
Give three Hash tables has some values.you need compare three hash tables and store the common values in fourth hash table?
Eliminate all ‘b’ and ‘ac’ in an array of characters, you have to replace them in-place, and you are only allowed to iterate over the char array once.
Examples:
abc -> ac
ac->''
react->rt
The bin packing problem is an example of a wide set of problems. The task is to find how many set sized bins are required to hold a number of differently sized boxes. How many bins (10 units high) are required to contain the following boxes (1,3,4 and 5 units high)?
Write a program to calculate the Loan Balance, where a person borrows an amount A and in return he/she agrees to make N payments per year, each of amount P. While the person is repaying the loan, interest will accumulate at an annual percentage rate of R, and this interest will be compounded N times a year (along with each payment). Therefore, the person must continue paying these installments of amount P until the original amount and any accumulated interest is repaid.
NOTE: The formula to calculate the amount that the person needs to repay after T years is -
Balance Amount after T years = A[(1+R/N)^NT]-P
Code to check if a given short string is a substring of a main string. Can you get a linear solution (O(n)) if possible?
Given a circular linked list, find the mid element of the linked list.
Explain how you would implement a multi-map in Java without using any collections?
Two numbers are represented as linked lists. Both lists are of same length. Add them without manipulating the lists and without a second traversal.
What is system.gc() and runtime.gc() ?
Which will take less time to retrieve the data if numbers are present in hashmap and sorted array .
An array of zero and non zero integer are their having range 10000 (i.e length of array is 10,000)
Arrange the array in such a way that zero comes first and after that the non zero integer.
Find duplicates in infinite range .
Which data structure to be used to give efficient solution.?
I answered HashMap .
How to implement using boolean array.?
You are given an application which sometimes may go into infinite loop.
Come up with a deployment plan s.t. the erring process is killed as soon as it goes into infinite loop.
Please consider the following tables:
Code:
Table Name: Person
Person_Id Name
Table Name: DVD
DVD_ID Owner_ID Title
Here is the query:
Write a query that returns the list of DVDs that belong to owners who own “Superman”
Here is my solution:
Code:
SELECT p.name,d.dvd_id
FROM DVD d,Person p
WHERE p.person_id = d.dvd_id
AND Title = 'Superman' ;
I answered above answer. But interviewer was expecting me to do using Subquery. Is that possible?Please let me know if the above query is correct or not.
Given a large file of (x,y) coordinates. Find the k farthest points from origin.
Given a network of printers and systems. Allocate the nearest printer to each system. How will you handle dynamic addition of printers and systems.
Given a sorted array which is rotated n number of times. Find out how many times the array is rotated. Time complexity should be less than O(n).
Given a Binary Search tree along with the parent pointer, find the next largest node for the given node. Give the time and space complexity. The node Structure is
class Node {
Int data;
Node left;
Node right;
Node parent;
}
Add a number to array and if there is carry increase array size.
---------------------------
For example input = {7,3,5,3,9} convert this to number 73539, add 1 so it becomes 73540 and convert to array {7,3,5,4,0}.
Array can be of any length, so you can't always represent array in form of in-built number format. So you have to do this summation in-place. Also, how would you increase array size in-case input = {9,9,9} so output = (1,0,0,0}
Assume, all elements of arrays are between 0 and 9.
Add a number to array and if there is carry increase array size.
----------------------------------------------------------------------
For example input = {7,3,5,3,9} convert this to number 73539, add 1 so it becomes 73540 and convert to array {7,3,5,4,0}.
Array can be of any length, so you can't always represent array in form of in-built number format. So you have to do this summation in-place. Also, how would you increase array size in-case input = {9,9,9} so output = (1,0,0,0}
Assume, all elements of arrays are between 0 and 9.
what is the difference?
void test(vector<int> vec)
{
//ptint the vec;
}
void test(const vector<int> &vec)
{
//print the vec;
}
Write a Javascript program for the following problem -
(Actually, any language is fine with me but it was a JS interview)
Given a large number of strings occurring on a web page, find the largest group of strings that are likely to be swapped with each other.
e.g mat, rat, groom, broom, cat
answer => mat, rat, cat and not groom, broom
I coded edit distance, got hopelessly lost beyond that.
As for hints, he said that it being a web page don't count on traversing a given string more than once.
How to write test data for a vendor machine using this coins (50 paise, 1 rupee coin, 2 rupee coin, 5 rupee coin, 10 rupee coin) to get (Tea, Coffee, Ice Tea, Cold Coffee, Milk)
Concept Is
Tea - 50 paise coin
Coffee - 1 rupee coin
Ice Tea - 2 rupee coin
Cold Coffee - 5 rupee coin
Milk - 10 rupee coin
A log file is of below format
log.txt
=====================================
TIMESTAMP:MM-DD-YYYY
REQUEST:______________________________
RESPONSE:____________________________
SUCCESS:200:________________________
=====================================
TIMESTAMP:MM-DD-YYYY
REQUEST:______________________________
RESPONSE:____________________________
ERROR:400:________________________
=====================================
TIMESTAMP:MM-DD-YYYY
REQUEST:______________________________
RESPONSE:____________________________
ERROR:=500:________________________
=====================================
TIMESTAMP:MM-DD-YYYY
REQUEST:______________________________
RESPONSE:____________________________
ERROR:400:________________________
=====================================
TIMESTAMP:MM-DD-YYYY
REQUEST:______________________________
RESPONSE:____________________________
ERROR:401:________________________
I want the count of error between two given dates.
grep '0[6789]:\| 1[01234567]' | ""grep -c "ERROR" log.txt
timestamp = grep "TIMESTAMP"
awk '$timestamawk>=from&&$timestamp<=to' from="2007/03/20 15:13" to="2007/08/19 14:31" log.txt | grep "ERROR" | wc -l
timestamp = grep "TIMESTAMP"
echo timestamp | awk -F'[- ]' '$2 >= 25 && $3 <= 04 { print }' | grep -c "ERROR"given an array of charactes have to replace space with %20. where %20 is considered as 3 characters.write complete code to implement this.
ps: assume that array has enough space at the end that can fit one space character to 3 chacters(%20).
import java.io.*
char fn(char [] word)
{
for(int i =1;i<=word.length();i++)
{
if(char[i]==" " && isArrayRightShiftable(word)){
shiftArrayToRight(word,i);
char[i]='%';
char[i+1]='2';
char[i+2]='0';
}
}
return word;
}
private boolean isArrayRightShiftable(char[] word)
{
if(word.length()+2 < 50){
return true;
}
return false;
}
private void shiftArrayToRight(char[] word, int i)
{
for(int j = word.length();j>=i;j--)
word[j+2]=word[j];
}Find the maxProduct of three numbers from a given integer array.
1. Handle all the cases
2. Interviewer was looking for a complete code
public int maxPro()
{ // -5, -4, -3, -2 , 0
Int array[] = new Int[]{4,5,6,0,-5,-7,-2,-10};
Arrays.sort(array);
// -10,-7,-5,-2,0,4,5,6
int count =0;
for(int i =0; i<array.length();i++){
if(array[i]<0)
count = count+1;
}
int maxProduct =1;
if ( array.length()<3){
return -1;
}
else if( array.length()>=3 ){
int a=1; b=2;
if(count>=2){
a = array[0]*array[1]*array[array.length-1];
b = array[array.length-1]*array[array.length-2]*array[array.length-3];
maxProduct = Math.max(a,b);
}
else if (count == 0 || count == 1 || count == array.length()){
maxProduct = array[array.length-1]*array[array.length-2]*array[array.length-3];
}
}
return maxProduct;
}write a generic function API in C so it can any data types like:
insert(a); where a can be integer,char,float
struct generic {
void *data;
struct generic *member
}
Reverse a string using C pointers
Ex: "Welcome to India" to "India to Welcome"
Reverse a binary number using bitwise operations in C
ex: 101101001 to 100101101
If two threads are incrementing a variable 100 times each without synchronization, what would be the possible min and maximum value.
Max distance between two nodes of binary tree. Distance is # of branches.
Design an algorithm to search for Anagrams of a word in a dictionary. The interviewer stressed on not processing all the words in the dictionary.
Sort an array which only has 0's and 1's. Do not use count sort.
I have table with columns (Employee, Manager, Salary). Need to calculate aggregate salary for all employees corresponding to top-level managers in one SQL. For example
Input table is :
Emp Manager Salary
A T 10
B A 11
C F 13
D B 5
Result should be :
Top-Lvl Manager Salary(agg)
T 26
F 13
Manager-Employee layering can go multiple levels.
Step 1: Write a Job Handler class that can handle multiple Requests that are trying to access a single Resource. Each Resource can only be allocated by one Requestor at a time. The requests should be handled in the order in which they are received by the Job Handler.
Step 2: Extend this class to handle multiple Resources.
Step 3: Do not allow the same Requestor to submit a Request for two Resources simultaneously.
Given a sorted array find whether odd number of numbers exist s.t. sum is K. 0 is a permitted value in array. Negatives may not be permitted. But he was not conclusive there. He was expecting Javascript code and O(n) complexity.
e.g. [12, 2, 1, 4] , searching 1 => yes, 5 => no because 4+1 make the number of numbers even!
Given an array find the subsequence that needs to be removed so that the array becomes sorted. There can be many resultant sorted arrays. Need to find longest. Expected time complexity O(n).
e.g. 9 9 6 1 3 4 4 5 1 7 => 1 3 4 4 5 7 so need to remove 9 9 6 1
Given a string, find the longest possible even palindrome (length of palindrome is even) from it.
Eg:
Input: abcicbbcdefggfed
Output: defggfed (length is 8)
Available palindromes are
1) bcicb - has odd length
2) cbbc - even length
3) defggfed - longest palindrome with even length
This question was asked in a telephonic interview for my friend. I will be posting his solution in a day.
Create a method which accept a integer as a argument and print on console. This method is accessed by multiple threads. If two or more threads call the method with same value then only one thread should allow to print the value other threads should wait. If values are different then all threads should allow to print the value.
Pairwise swap elements of a given doubly linkedlist.
Node has prev and next pointers.
We have a very large excel file that is produced every day by a batch process. We need to report what records were added and which records were removed compared to the file generated on the previous day. The challenge is that there is no sortable field in the list that we could use (such as a creation date), imagine for the sake of this test that there’s only First Name, Last Name and Email in the excel file, and that the ordering is not consistent from one day to the next. How would you approach the problem?
There is a sorted array of integers (suppose sorted in "ascending order"). How will you find a specific element in an array? You can not use traditional iterative method to find a specific element in an array.
Write inorder traversal without using recursion.
Add two integers which cannot be stored even in long long int.
write a program to serialize and deserialize a Binary tree
you have a set of integers between 1 .. n in a random order with one of the numbers being repeated. find the best possible way (time and space) to obtain the repeating number.
write a program to return the highest value from a binary tree (note: not BST)
write a program to validate a BST and state the complexity (assume payload is integer values)
For 2 given array a[] and B[], find the highest index of A such that logical array A[0...i] and A[N-1...N-1-i] are same.
Data-structure and algorithm used in Load Balancer??
Explaining algorithm write code for it
Function to reverse a c style sub-string
start - points to the first character to be reversed
end - points to character after the last character to be reversed
Note: STL not allowed
void reverse(char* start, char* end)
1. N-Petrol bunk problem: There are n petrol bunks located in a circle. We have a truck which runs 1 km per 1 liter (mileage 1kmpl). Two arrays are given. The distances between petrol bunks are given in one array. Other array contains the no of liters available at each petrol bunk. We have to find the starting point such that if we start at that point , you we would able to visit entire circle without running out of fuel. Initially truck has no fuel
How can you make thread safe to 3rd party library javaclass.
Implement circular queue in Java such that:
1. It should work in multithreaaded environment.
2. If one thread performing EnQueue operation and if queue are full then it should wait untill other not emptied the queue.
3. If some thread tring to do Dequeue operation and if queue is empty, then that thread should wait untill other thread can fill atleast one element in queue.
Write a Program such that
1. Thread T1 and T2 are doing job J1 and J2 respectively.
2. Job J2 can't be start by J2 untill job J1 is done by J1.
3. Write code without using Join() method.
write a code to print the second largest element in a list
Shortest possible complexity.
Q1. What is inheritance
2. Polymorphism
3. Diff between Pure Virtual class and Virtual Class
4. Adv and dis-adv of C# and C++ over each other
5. Sequence in which constructors are called when a child class object is created and why is the order so.
Given a rotated sorted array, find the MIN of the array.
He pointed out a mistake in my
int middle = (begin+end)/2 which could overflow if the array size was INT_MAX.
Answer was:
middle = (end-begin)/2 + begin
Given a binary tree, print its perimeter:
node, left->most nodes from top to bottom, leaf nodes from left-> right, right->most nodes from bottom to top
----------------------------1
-----------------------2--------3
------------------4-----5-----6--------7
-------------8------9-----10------11-----12
should print:
1-2-4-8-9-5-10-11-12-7-3
5 because it doesn't have any children. 10 and 11 are children of 6 and 8 & 9 are children of 4.
Apologies for the messy diagram.
Given a Binary tree and a node, return it's post-order predecessor
Single Initialization :
Global variable x, initialized to 0.
Implement a function that can be called by multiple threads simultaneously or sequentially.
The value of x should be set to the current time only once. If it is already set, the value shouldn't be updated.
Make sure that the function doesn't become a bottleneck
Given a BT and 2 nodes, find LowestCommonAncestor
Find the Max sum subsequence in array
There is a HealthMonitor and two Servers (Primary and Secondary), all connected to one and another.
The HealthMonitor keeps pinging both the servers at specific time intervals and waits for their response for a time-out period after the request has been sent.
The server responds with a health status of itself and of its neighbor (meaning Primary responsds: OK; NEIGHBOR_OK)
Implement the server's code to send and receive responses and then take action based on response.
Write a class that will have following functions:
long CheckOut()
CheckIn(long)
Range of values is 1 to LONG_MAX
At any given point in time checkout should return the minimum available LONG number
Checkin can return the value back
No need to check for border conditions (e.g. check out when all values are exhausted)
Implement:
1. long checkout()
2. void checkIn(long input)
Write a class For Contacts on a device
Implementing Search a contact was the biggest problem I faced (because search should potentially search: FirstName, LastName, Address, PH#, Email etc)
Write a class for a parking garage:
One level
One entry point
No membership or payments required
Handles multiple types of cars
Implement:
1. a search that will return all the strings that match a sub-string
2. an insert into this datastructure
Class
{
Insert (string str){};
List<strings> Predictions(string subString){};
}Implement an iterator for a Binary tree. It should have the following things:
1. bool HasNext()
2. <T> Next()
It should be an in-order traversal.
How could you make sure that thread A ,B and C run sequentially without using join method?
You have a string str = "I love you".
Write a program to print the output as "you love I". Calculate the efficiency of your coding.
What design pattern does AOP use?
You have two class A and B in a jar file and you have no source code with you. Write a class C which will rewrite the behaviour of the methods in A and B. You are not allowed to write any other class or interface.
Write program of thread pool.
You have an array Char[] chArray = {'a','a','b','c','a','b','d','c','c','d','a','a'}
Write a program to remove the duplicate and the output should be as per the below:
{'a','b','c','d','','','','','','',''} . You should not use any collection api
What design pattern does Exception handling use and why?
Why do we have both checked exception and Runtime Exception? What will happen if we have only one of a kind?
You are in a maze, and you need to find all possible path from an entrance to an exit. Here are the constraints: ● The maze is represented by a 2D grid. ● Spots that you can step on are represented by a 0. ● Pits that you will fall into (aka spots that you cannot step on) are represented by a 1. ● The entrance is represented by a 2. ● The exit is represented by a 3. ● Each path can only have two endpoints; entrance and exit. You cannot use the entrance or exit more than once for each path. ● You have to step on every spot exactly once. ● You can only move like a King in chess (horizontally or vertically but not diagonally)
Here is an example of the maze: 2 0 0 0 0 0 0 0 0 0 0 0 0 3 1 Possible paths are:
Your program should read from standard input with a series of integers with whitespace as delimiter. The first two integer represents the width and height of the maze. It will then be followed by width*height more integers. Your output should be an integer which shows the total number of possible path. Marks will be given for efficiency as well.
A List PARENTLIST which contains primitive type and List L, this List L further can have primitve type and List L and so on. Given a Root node calculate how many List it have
What is stale object in Java? How will you handle it? For example: You have a Class A as shown below
public class A{
A(){
// code for database connection
}
// code for other method
}
Now,you are trying to create a object A by its constructor. To initialize constructor it throws some exception to create database connection.
A obj = new A().
obj.amethod() ;
If obj.amethod() ; will be executed successfully or not ?
How will you stop your code not to use obj?
For a given number, print this number in words(in Indian style number system).
eg:
i/p 345 o/p: three hundred fourtyfive
i/p 3145 o/p: three thousand one hundred fourtyfive
i/p 314520 o/p: three lakh fourteen thousand five hundred twenty.
* http://en.wikipedia.org/wiki/South_Asian_numbering_system
If a function is der mostCommonChar(String str, int num) ,
1-.First input is Aabra Ka Daabra and second argument is 1 then the function should return first most repeated character in the string .Means in sorted descending .
2-> First input is Aabra Ka Daabra and second argument is 2
then the function should return second most repeated character in the string
like wise 3rd 4rth ....etc
Write a C program to find the number of shift required to convert one string to another. Check all the corner cases.
Eg: abc to acb o/p shd be 2 as 'b' shifted from 1st index to 2nd and 'c' shifted to 1st from second.
You have a very large file of integers which cannot be loaded into memory at once. How would you find the ten largest numbers of that file?
Let A be an array of size n, containing positive or negative integers, with A[1] < A[2] <...< A[n]. Design an efficient algorithm (should be more efficient than O(n)) to find an i such that A[i] = i provided such an i exists. What is the worst case computational complexity of your algorithm?
Problem statement
You are planning a big programming conference and have received many proposals which have passed
the initial screen process but you're having trouble fitting them into the time constraints of the day -- there
are so many possibilities! So you write a program to do it for you.
· The conference has multiple tracks each of which has a morning and afternoon session.
· Each session contains multiple talks.
· Morning sessions begin at 9am and must finish by 12 noon, for lunch.
· Afternoon sessions begin at 1pm and must finish in time for the networking event.
· The networking event can start no earlier than 4:00 and no later than 5:00.
· No talk title has numbers in it.
· All talk lengths are either in minutes (not hours) or lightning (5 minutes).
· Presenters will be very punctual; there needs to be no gap between sessions.
Note that depending on how you choose to complete this problem, your solution may give a different
ordering or combination of talks into tracks. This is acceptable; you don’t need to exactly duplicate the
sample output given here.
Test input:
Writing Fast Tests Against Enterprise Rails 60min
Overdoing it in Python 45min
Lua for the Masses 30min
Ruby Errors from Mismatched Gem Versions 45min
Common Ruby Errors 45min
Rails for Python Developers lightning
Communicating Over Distance 60min
Accounting-Driven Development 45min
Woah 30min
Sit Down and Write 30min
Pair Programming vs Noise 45min
Rails Magic 60min
Ruby on Rails: Why We Should Move On 60min
Clojure Ate Scala (on my project) 45min
Programming in the Boondocks of Seattle 30min
Ruby vs. Clojure for Back-End Development 30min
Ruby on Rails Legacy App Maintenance 60min
A World Without HackerNews 30min
User Interface CSS in Rails Apps 30min
Test output:
Track 1:
09:00AM Writing Fast Tests Against Enterprise Rails 60min
10:00AM Overdoing it in Python 45min
10:45AM Lua for the Masses 30min
11:15AM Ruby Errors from Mismatched Gem Versions 45min
12:00PM Lunch
01:00PM Ruby on Rails: Why We Should Move On 60min
02:00PM Common Ruby Errors 45min
02:45PM Pair Programming vs Noise 45min
03:30PM Programming in the Boondocks of Seattle 30min
04:00PM Ruby vs. Clojure for Back-End Development 30min
04:30PM User Interface CSS in Rails Apps 30min
05:00PM Networking Event
Track 2:
09:00AM Communicating Over Distance 60min
10:00AM Rails Magic 60min
11:00AM Woah 30min
11:30AM Sit Down and Write 30min
12:00PM Lunch
01:00PM Accounting-Driven Development 45min
01:45PM Clojure Ate Scala (on my project) 45min
02:30PM A World Without HackerNews 30min
03:00PM Ruby on Rails Legacy App Maintenance 60min
04:00PM Rails for Python Developers lightning
05:00PM Networking Event
Adding Very Large Numbers. Write clean code for it. please check all corner cases..
Number can be really really large
Design a singleton design pattern.
Design a class in C++ such that only one object of it can be created.
Given 'n' coins, print the number of ways to form an amount 'A' . This is a standard denomination problem with one small twist(We have only one coin of each type,not infinite number,if we choose one coin for making change we should not choose it again) . Can somebody give a code with explanation ?
Example:
Amount:3 coins : 1 2 3
There are only two ways (1,2)(3) not (1,1,1)(1,2)(3)
Find the 3rd closest element in a bst.You will be given a pointer to root and a value within the tree against which the closest has to be figured out. (closeness is in terms of value, not by distance ) and then follow up qn: for finding the kth closest in a bst.
Consider a city with 50 locations each numbered from 0 to 49. Mr. XYZ runs a taxi service in a city. He has 25 Taxi’s to service the passengers. When passenger needs a taxi he makes a call to Mr. XYZ and give details like his current location as a source, and where he is willing to travel as a destination. He also tells max time he can wait for a taxi. In return Mr. XYZ either allocate a taxi to the passenger or tell him request can’t be satisfied within the given max_waiting time. Allocated taxi travels from its current location to the passengers pick-up point i.e. the source. This travel is termed as non revenue travel. Mr. XYZ charge passenger only for the distance from source to the destination. After dropping passenger to the destination taxi waits for call from Mr. XYZ to serve next passenger.
Let’s assume we know all TaxiHireRequests in advance. We also know the distance and time to travel between any two locations in the city.
Write a program which will choose the taxi’s such that sum of non_revenue distance travelled by all the Taxi’s is minimum and the number of unsatisfied requests are minimized. Also print the total non_revenew distance and number of unsatisfied requests.
pseudo helper structures.
struct TaxiHireRequest{
int Time Of Request;//Number of seconds from 12AM
int Source; // an int from 0 to 49
int Destination;// an int from 0 to 49
int Maximum waiting time // in seconds;
}[200]
struct Taxi{
int location;//an int from 0 to 49
bool isHired//true or false
}[25]
int Distance[50][50];
int Time[50][50];
// Extend the structure whenever required.
What is K&R ?
What is NP-complete? what does NP stand for?
How many bits of IPv4 and IPv6?
Find the sub-array in a given array A, sum of elements of that sub-array is divisible by N(array size).
A video streaming server is generating the following data. Find the potential customers facing buffering issues.
A person is said to face buffering issues when he hits the play button multiple times on the same video
You are given a huge file (say 1GB) that contains the following data:
CustomerId-TimeStamp-Event-VideoId-Videolength
0040 -01.00pm -Play -Video1 -02:30:00
Write code for this. What data structure will you use
He also said, lets say all the parsing is taken care of and you are given a collection of classes that contain the above data:
Class
{
CustomerId
TimeStamp
Event
VideoId
}Design an online hotel reservation system.
(I think this has been posted in Careercup earlier)
Design a furniture store with Tables and chairs. Write a constructor for chair and table
You are given a UNIX path with dot (current) and two dots (parent). Convert this to an absolute path
E.g. $/home/abc/.././def/./ghi/../.
becomes $/home/ghi/
You are on a point on Google Maps (longitude, latitude). You select a radius, and expect to get a list of all the places within that radius. How would you implement this?
How would you implement live search for people's names (only firstname and lastname, or lastname and firstname) like in facebook's search, retreiving the top 5, knowing a value between 0 and 1 for every one of them. If you are close friends then the value will be bigger. You should output the first 5 values in descending order.
Write a program to calculate Sum of two singly linked lists.
e.g.
1-->2-->3
8->9->10
.
Result list should be 10-->2-->3
You are not allowed to make any change in input lists. Those are read only.
Given a non sorted array consisting 0's and 1's. find the index of first '1'. write a complete program which takes less time complexity. and test all boundary conditions also.
Eg: If given array is 0,0,0,1,0,0,0,1,1,1,1 the out put should be 3.
following coins: half dollar, quarters,dime, nickel and penny. Print all the possible combinations of coins that will equal to one dollar.(Ex : (2) half-dollar , (4) quarter dollar etc )..
Given N dices.Each dice has A faces.That means each dice has numbers from 1 to A.Given Sum S,Find the number of ways to make the sum S if dices are rolled together.
Given a BST find Ceiling value of given key
8
6 12
2 4 11 14key = 8 return 11
key = 1 return 2
key = 16 return Null
Iteration and Recursion both
Q:
Given a binary tree with nodes that have left, right pointers pointing to the left and right children respoectively. It also has a neighbor pointer that currently Points to null.
Write a function to make it point to its neighbor.
E.g
1
2 3
4 5 6 71.sibling should point to null
2.sibling should point to 3
3.sibling should point to null
4.sibling should point to 5
5.sibling should point to 6
6.sibling should point to 7
7.sibling should point to null
Iteration and Recursion both
4 men- each can cross a bridge in 1,3, 7, and 10 min.
Only 2 people can walk the bridge at a time. How many min. minutes would they take to cross the bridge.
write a class which exposes only 20 of its Objects containing two methods borrowObject and returnObject .Code must be thread safe.Also write a method to get the number of Live Objects(Objects currently in use by other classes).
The probability of a bus passing through a certain intersection in a time window of 20 min. is 0.9
What is the probability of the same bus passing through the same intersection in 5 min.
Input is given a binarytree and out is sum of the all the children data and its node data .
Eg:
1 28
2 3 11 16
4 5 6 7 4 5 6 7
Given a sorted array consisting 0's and 1's. find the index of first '1'. write a complete program which takes less time complexity. and test all boundary conditions also.
Eg: If given array is 0,0,0,0,0,0,1,1,1,1 the out put should be 6.
Explain Collaborative Caching?
There are lots of string in a file. Find the longest string that could be made from the other strings in the file.
Eg.
the
there
after
thereafter
reaf
ans.
thereafter
Which data structure we can use to represent many to many relationship in a memory.
i.e A URL is opened at multiple timestamps and single timestamp can be related to multiple URLs
How does DropBox work ? Say if you have 25 Gb space granted to you by DropBox, does it mean that DropBox application when installed on Desktop will allocate 25 GB of your space ? Or does it keep only the recent used files on system and METADATA for all the files. Please suggest.
You are given a set of 8 balls, all of them identical in appearance and weight, except for one which is slightly heavier than the rest. You are also given a scale with no units, which can only tell you if one load is heavier than the other (think a scale-of-justice type scale). How can you find the heavy ball with only two comparisons? You may place as many balls as you wish on either side of the scale for each comparison.
Given an integer N, populate an array of size N with the first N sum-of-squares. In other words, if you were given N=3, your array would be [1, 5, 14] (1^2, 1^2 + 2^2, 1^2 + 2^2 + 3^2).
How do you find the greatest 1000 elements in a list of a million elements? No other information given. What would be the runtime? Hint: You can do better than O(n log n). I didn't realize but it could be possible with Tree or Heaps.
Flatten a List<List<Integer>> in Java and implement the hasNext() and next() methods.
e.g. [[6,8],4] should return true when at 6, 8 and false at 4.
Given an array A of length n where each element is 1..k where k is much smaller than n,
find one set of distinct indices i1 and i2 such that A[i1] + A[i2] == z.
Suppose we want to convert one string S1 to another string S2 using only 3 types of operations:
-Insert(pos,char) (costs 8)
-Delete(pos) (costs 6)
-Replace(pos,char) (costs 8)
Find the sequence of steps to convert S1 to S2 such that the cost to convert S1 to S2 is minimum.
Eg. 'calculate' to 'late' - the possible operations are
Delete(0)
Delete(1)
Delete(2)
Delete(3)
Delete(4)
and the above sequence of operations costs 30.
I used the following code(using levenshtein algorithm) to solve this. But I am not getting correct answer.
tuples=[]
ops=[]
s1=''
s2=''
def levenshtein(a,b):
global s1,s2
n, m = len(a), len(b)
if n > m:
a,b = b,a
n,m = m,n
s1,s2=a,b
current = range(n+1)
for i in range(0,len(current)):
current[i]=current[i]*8
tuples.append(current)
for i in range(1,m+1):
previous, current = current, [i*8]+[0]*n
for j in range(1,n+1):
add, delete = previous[j]+6, current[j-1]+8
change = previous[j-1]
if a[j-1] != b[i-1]:
change=change+8
current[j] = min(add, delete, change)
tuples.append(current)
return current[n]
print levenshtein('calculate','late')
for i in range(len(tuples)):
stri=''
for j in range(len(tuples[0])):
stri+=str(tuples[i][j])+' '
i=len(tuples)-1
j=len(tuples[0])-1
ops=[]
while i>0:
while j>0:
minimum=min([tuples[i-1][j],tuples[i][j-1],tuples[i-1][j-1]])
if minimum==tuples[i-1][j]:
i=i-1
if not tuples[i][j]==tuples[i-1][j]:
ops.append([1,i])
elif minimum==tuples[i][j-1]:
j=j-1
if not tuples[i][j]==tuples[i][j-1]:
ops.append([2,i-1,j])
else:
ops.append([3,i-1,s1[i-1]])
i=i-1
j=j-1function takes input x , y , A and N
returns true if
there are atleast N pairs of x and y satisfying
x^3 + y^3 = A;
all inputs are postive integer values
Code to create a file system.... Have classes like directory, file and all
please write the full code
In a BST, I want to replace all nodes with value which is the sum of all the nodes which are greater than equal to the current node.
5
2 10
Output -->
15
17 10
You are given a BST, and min, max elements. Your task is to trim this BST so that it contains the elements between the min and the max elements.
For example, given the mix and max elements [5, 13] and the tree below, you would return the output below.
8
3 10
1 6 14
4 7 13output should be :--->
8
6 10
7 13Design a DS for storing browsing history.
Design a Calculator. Details about the class variables, datastructure to be used etc.
Generate a solution when multiple threads want to just read in their critical sections and when nobody is writing in the critical section.
Implement a simple regex parser which, given a string and a pattern, returns a boolean indicating whether the input matches the pattern. By simple, we mean that the regex can only contain one special character: * (star). The star means what you'd expect, that there will be zero or more of any character in that place in the pattern. However, multiple consecutive stars are allowed. Some examples of valid input (and expected output):
f(a*b, acb) => true
f(abc*, abbc) => false
f(**bc, bc) => true
Design a class structure for an airport terminal, where your primary use case is allocating runway time to approaching aircraft. For example, an instance of a terminal may have only two runways of different lengths and must schedule these among five aircraft of different types requesting permission to land.
Write a service or services to support tic-tac-toe between two players, on an infinite board. Normal rules apply (i.e. three in a row to win), but the players are not limited to a 3X3 board and can choose to place an X or an O in any arbitrary, positive (i, j) position. Solution should be as space and time efficient as possible. Your service is only responsible for maintaining and updating the state of the board between two players, given their sequence of moves.
How to print a variable 1000 times without using loops and recurssion
Finding border of a binary tree.Given a Binary tree print all the nodes that form the boundary.
For given N* N matrix,
1 2 3
8 9 4
7 6 5
Write a program to
print 1,2,3,4,5,6,7,8,9
write a function :
char * CreateEmptyString(int len);
function should return an pointer to an empty string of length len
Design a LRU cache in Java.
Write a code in java to design connection pool. You have to pass the parameter like pool size, time out etc.
How will you call the connection from pool?Write the code in Java?
How will you return the connection to pool once time out or connection not in use. You also have to write the exception handling mechanism to print any exception.
Write a SQL to find the nth maximum salary in a employee table.
You have a very very big text file.How would you read & process it to print the below output.
1. Print the top ten ranked distinct words.
2. Print the occurrence of the each alphabet in this file.
For example:
ABC (100)
XYZ (40)
PQR (10)
THE (200)
IN (200)
Then I have to display the output as
IN (200)
THE (200)
ABC (100)
XYZ (40).
And
A=1000
B=2000
C= 300
.. ...
z=300
There is a 1.2G text file on the 1.5G hard drive and 300M memory, how can reverse these file in word unit.
please program with c language!
For example:
"Thank you for your help"
reversed:
"help your for you Thank"
how do you handle your thread, to avoid dead lock and efficient(generally question)
what is Materialized view, is any different from View.
Truth Table implementation: Write a function which takes integer as In put parameter (let's say n), print all True (T) , False (F) combinations n times. Here is the example:
for n = 1
Output :
T
F
for n = 2
Output :
T F
F T
For n = 3
Output :
T T T
T T F
T F T
T F F
F T T
F T F
F F T
F F FWrite a program to swap kth node from first and kth node from last in a linked list .
write a java program to reverse a string.
Write a java program to read a file and get different words and also print number of occurences of each word.
Design a MMORPG game in internet scale. Assume only available action for the players is watch and move.
Given a matrix that contains 0s and 1s, find the shortest exit and print the path. You can navigate in top,bottom,left or right directions.
In a stream of numbers, keep track of 1 million max numbers.
find the Langford sequence for a given N if it exists? Details of Langford sequence - https://en.wikipedia.org/wiki/Langford_pairing
C program to convert little endian to big endian. Implement htons. ?
Also convert little to big endian using UNIONS ?
Given a sequence of numbers (or array).Find the maximum distance between all the same numbers.Like you have 1,2,3,4,1,1,7,4 so max(1)=5,max(2)=0 max(4)=4. etc.
Given an array of integers, find all sub-arrays whose elements sum zero.
1.-1,4,-4 has 3 such arrays 1 to -1, 1 to -4 and 4 to -4
Write a java program to count the words from the file Othello.txt
- Have the stop words library to filter the words like (to, the, and). (We do not want to count these words)
- Measure the time taken to execute the code.
Small input (From File) : othello.txt
Output (In Console) :
Welcome - 1
bhive -1
community - 2
Join -1
win - 1
exciting - 1
prizes -1
Time Taken: 100 milliseconds
Bigger Input (From File) : othello.txt
Does your code execute within 10 seconds?.
//Q. Given an array of integers,write a function that retrieves unique instances of any duplicates, returning them in a //new array -
// [2,1,2,4,3,1,5,1]
//= [2,1]
// [1,1,1,1,1,1,1,1,1]
// =[1]
// Write test cases for this function
Q: If you have all the companies that are traded, and live inputs are coming of which company is being traded and what is the volume, how do you maintain the data, so that you can carry out operation of giving the top 10 most traded companies by volume of shares most efficiently.
A: I juggled between Hash Map and Max Heap. I said Max Heap, since I can take out top 10 companies in a jiffy with a Max Heap. But then he asked you will need to find a company everytime there is a trade, which will take quite some time in Heap. He pointed out that in real world scenario, number of trades happening, and hence searching of the company and updating it, will be many times more than finding top 10. Which bought me to HashMap. Updations can happen in Real time, while finding top 10 can be done in O(n) or O(nlog(n)) time.
Even that wasn't optimal obviously. The interviewer was very nice and friendly type guy. He stressed that at every trade, at most, only 1 company will change in my top 10. This hit me and got me to the correct answer that we keep all actual data in HashMap, but also maintain a MinHeap of 10 most traded company.
Q: If I give you a new book, and ask you to create the index which is found at the end of the book, how will you do it.
A: I said for constant addition time of words (and page numbers) in the data structure, we can use Hashmap or TRIE. But since output has to be in alphabetic order, we will use a Trie DS, where at the end of each word, we simple store a list of page numbers.
Q: The New operator...how does it work, what are the steps?
A: I just said it creates a new memory in the heap and the reference points to it. He seemed satisfied.
Q: Do you know what is a Binary tree? How would you go about coding for addition of a new element to Binary tree?
A: I asked if they want a Binary Tree or a BST? When he said BST I just said we can have a recursive function in which we pass the root of the tree and see if the value to be added is smaller or bigger than the root, and depending on result, we go to left or right of the tree, assuming the left (or right) is not null. If null, just use new to create a memory location, put the value, and use the left reference of the root to link to this new memory. Simple basic stuff.
Q: Do you know what is a stack? Explain
A: Yes, explained LIFO push pop peek
Q: In stack, Push and Pop are constant. What will you do if you want an operation which gives the min of the stack also in constant time?
A: Question is straight out of Gayle's Book. You just maintain a new stack of minimum number till that point.
Implementation of Advanced set which have the functionality as "Set" in c++ along with extra functionality-Random number generator.Returns the random number from the set.
Given a directed acyclic graph.How to represent it in the relational database for efficient retrieval of all the children nodes and all the parents of any node.(ex a->b here b is child of a and a is parent of b)
Given a string.Find the longest substring in it such that the substring contains only 2 unique characters.Ex- aabbcbbbadef Ans-bbcbbb
In a party there are n different-flavored cakes of volume V1, V2, V3 ... Vn each. Need to divide them into K people present in the party such that
- Each member of party gets equal volume of cake (say V, which is the solution we are looking for)
- A given member should get a cake of single flavour only i.e. You cannot distribute parts of different flavored cakes to same member.
- Minimum volume of cake gets wasted after distribution so that means a maximum distribution policy
How do you remove duplicates from a dataset that does not fit into memory?
Find the merge point of two linked list.
3)Reverse individual words of a sentence.
Reverse an integer without using temp variable.
How to swap two bits in an integer.
In a shop, product X is available in different quantities q1,q2,q3...... with price tags p1,p2,p3,...
wap to purchase X of quantity Q such that total price is less and also number of baggage is less
*Consider the cost to be optimum than baggage.
(Sorry the trouble guys, I have edited the ques here)
Wap to find kth largest element in a binary search tree
Given a binary tree convert it to doubly linked list, with left pointer of binary tree as prev pointer of doubly linked list and right pointer of binary tree as next pointer of doubly linked list.
Example:
Input:
Binary tree with
A as root
B left of A
C right of A
B&C have no children
Output:
B->A->C->null
null<-B<-A<-C
Given a linked list, print n nodes from tail of the list in reverse order
Example:
1->2->3->4->5->6->7->8->9->10
Output:
n=3
10->9->8
What will be the output of the program ?
#include< stdio.h >
void fun(void *p);
int i;
int main()
{
void *vptr;
vptr = &i;
fun(vptr);
return 0;
}
void fun(void *p)
{
int **q;
q = (int**)&p;
printf("%d ", **q);
}
test(){
return 3;
}
void main(){
int i=2;
for(test();test();test();)
{
printf("2");
}
Output value or run-time error or compile time error ?
Given an array A of integers, find an integer k that is not present in A. Assume that the integers are 32-bit signed integers.
Given sorted arrays A and B of lengths n and m respectively,return an array C containing elements common to A and B. The array C should be free of duplicates.
In a 5*4 matrix what is the most optimal way of traversal and compare the time complexity for different solution ?
How can you implement a Hashtable with any given data structure
What is hash function
How can you resolve collisions
Given an integer array, return the combinations of 4 array values whose sum is x
Eg:
Input int array = {1,2,3,5,0,-2}
Return all possible combinations such that
a+b+c+d = 1
Like: -2 , 0 , -2 , 5
2 , -2 , 0 , 1, etc...
Car has two sides.One side A B C and other side a b c
WAP to print all the combinations. Positions are not changed.
Eg: for the above you will get 8 combinations.
ABC
AbC
ABc
Abc
aBc
aBC
abC
abc
Create a Session Manager class that iterates thru Session objects throw stale sessions out - How would you automatically purge Session objects that have not been active for 30 seconds or (n) seconds? The answer needs to handle millions of sessions.
Write a C program to search for a given pattern from various files in a directory without using grep or any other inbuilt command
I Got this Crazy Question on PHONE INTERVIEW AT GOOGLE:
Design and implement a class to generate random numbers in an arbitrary probability distribution given by an array of integer weights, i.e. for int[] w return a number, n, from 0 to w.length - 1 with probability w[n] / sum(w). Using an existing random number generator with a uniform distribution is permitted.
Example distribution:
w = 1, 2, 3, 2, 1
Example probabilities:
w / sum = 1/9, 2/9, 1/3, 2/9, 1/9
Example results:
n = 0, 1, 2, 3, 4
Documentation:
Class java.util.Random
public int nextInt(int n)
Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive), drawn from this random number generator's sequence. The general contract of nextInt is that one int value in the specified range is pseudorandomly generated and returned. All n possible int values are produced with (approximately) equal probability.
Parameters:
n - the bound on the random number to be returned. Must be positive.
Returns:
the next pseudorandom, uniformly distributed int value between 0 (inclusive) and n (exclusive) from this random number generator's sequence
Throws:
IllegalArgumentException - if n is not positive
Youtube is not playing the selected video. What could be the problem and how to debug this issue?
Write a program to check whether a substring is present in a main string.
Write all possible test cases for SMS (Short Messaging Service) on a mobile device.
Given the fact that you have a map <SessionId, SessionValueObject> , . The sessionValueObject contains timestamp as well associated with the session. In generality, we are maintaining a key value pair. And each session has a timestamp associated with it.
Now the question was given a particular timestamp associated with a sessionValueObject, we need to implement a data structure such that,
given a timestamp t1, we need to free/ remove all the sessionValueObjects associated after the timestamp t1.
How do we do this efficiently?
Data Structure for node of linked list
Find the nth node form end of a linked list and also write test case
i have given solution with o(n) after that they asked to me how to break the my algorithm
Design an algorithm to remove the duplicate characters in a string without using any additional buffer. NOTE: One or two additional variables are fine. An extra copy of the array is not. also do with o(n2),o(n),o(1) ,write test case and breake the algorithm whatever you write.
Given a mathematical expression, remove the redundant brackets from the expression.
e.g. input: (a + (b*c)) * (d * ( f * j) )
output should be: (a + b * c) *d * f * J
operations to support: +, -, /, *, ++, also ternary operators.
Length is given as input.Print all possible permutations of numbers between 0-9.
Eg: if input length=4
all possible combinations can be 0123, 1234, 5678,9864,...etc all combinations of length from in all numbers between 0-9
Let's say you have a fixed thread pool of size 1, internally how does this threadPool work? How is that the same thread gets used again and again.
-------
My answer: The run() methods from various classes are loaded on to a task Queue. As and when the tasks get added to to this queue, the thread keeps on acting on this queue.
Something like:
Queue qTask = new Queue();
qTask.enqueue(object1.method1());
qTask.enqueue(object2.method2());
...
public void run(){
while(true){
if (qTask == null or empty){
wait()
}
//Take tasks out of qTask
}What are the disadvantages/limitations of a ConcurrentHashmap in JAVA?
Given a huge file, design a data structure to output all possible anagrams of a particular word.
For Eg the file contains: "POT, OPT, TOP"
If I query for POT, I should get back all possible anagrams contained in the file.
--
Write a program to reverse the sequence of words in a sentence.
For Eg:
String str = "Today is Wednesday";
Output:
String str2 = "Wednesday is Today"
Write a function to populate the best (lowest cost) path in a 64x64 weighted grid from a given start cell to a destination cell.
Create a basic implementation of Deferred.
Deferred#resolve => Marks the deferred / promise as completed successfully and calls success callbacks
Deferred#reject => Marks the deferred / promise as failed and calls failed callbacks
Deferred#promise => Returns promise object for watching completion
#addCallback => Adds a callback function to be called if the activity is successful
#addFailCallback => Adds a callback function to be called if the activity fails
var promise = myAsyncThingy(); // Call the API that starts some async work and returns a promise
promise.addCallback(function () { console.log("We did it"); }); // Register a success callback
promise.addFailCallback(function () { console.error("We failed"); }); // Register a failure callback
function myAsyncThingy() {
var def = new Deferred(); // Create a deferred to use for managing our async behavior
setTimeout(function () { def.resolve() }, 1000); // In one second call the resolve function to mark it as success
return def.promise(); // return the promise for our deferred to the client
}
Using the mythical Hydra as an example, create a button that is destroyed by clicking it, but two new buttons are created in it's place.
Create a function that will reverse the words in a sentence.
Design a task scheduler
Design a vending machine.
array of numbers are given. WAP to find the sum of contiguous subarray within a one-dimensional array of numbers which has the largest sum.
Follow up: After writing program to return the largest sum modify it to return the start and end index of such a subarray.
Given an array with source code and braces (braces means '{' or '}' ) intermixed. WAP to return true of braces are balanced (implies that for each opening brace there must be a closing brace and for each closing brace there must be opening brace) and false otherwise.
Given a pattern P and a text T, WAP to return all indices from T where P matches.
Position of Knight is given on a chessboard.
Return me something (adjacency matrix or list or anything) which shows all
the positions the knight can reach upto from a given position.
I must be able to tell, from what is returned, if the position is reachable or not
and if reachable I must be able to trace the path from given position to target position
<<FOLLOW-UP>>
For example if 4 cells are reachable from a cell A, then these 4 cells become children of A.
Then from a cell, say B, out of these 4 cells, you can reach 2 more cells: C and D. Then C and D become children of B.
Likewise program need to return me a DS. I have given a valuable hint with this follow-up. I hope this will help
How would you test ios simulator ? or How would you test an Android simulator ? note: the questions asks for how would you test the simulator itself and NOTapplications
You have unique ASCII characters. How you can sort them ?
Run time complexity of approach ?
N boys are sitting in a circle. Each of them have some apples in their hand.
You find that the total number of the apples can be divided by N.
So you want to divide the apples equally among all the boys.
But they are so lazy that each one of them only wants to give one apple to one of the neighbors at one step.
Calculate the minimal number of steps to make each boy have the same number of apples.
Input Given:
1. A number N => number of children.
2. Sequence of N numbers, each representing number of apples a child has.
<<P.S.>>
Passing an apple means a child giving away one apple to one of its neighbour.
Even if 2 separate children can pass apples simultaneously or one child can pass 1-1 apple to each of its neighbours then that will still be counted as 2 steps and not 1 step.
which of the following is true for static member of the class?
a) internal linkage
b) external linkage
#include<iostream>
#include<exception>
int main()
{
try
{
cout << "sum";
throw 3;
}
catch(...)
{
cout<< "dot";
}
catch(int a)
{
cout << a;
}
catch(exception e)
{
cout << "exception";
}
return 0;
}
what will be the output of the above program?
For the written test please prepare the following topics throughly :
a) virtual function
b) operator overloading
c) namespace
d) template
For interview, please prepare the container throughly with the implementation of list,map etc.
class a{
public:
int var1;
a(int var)
{
var1 = var;
}
};
class b: public a
{
public:
int var2;
b(int d) : var2( d++) , a(var2++)
{
}
};
int main
{
b obj1(5);
}
What will be the value of the variable 'var1' in class A?
a) 6
b)7
c) 5
d) undefined
class a{
public:
int a;
virtual void sum() {
printf("sum");
}
};
class b : public a {
public:
int b;
virtual void sum() {
printf("sum of class b");
}
};
void main() {
b aptr;
a *bptr;
bptr = &aptr;
bptr->sum();
}Output of the above program?
Why the size of the empty class is one?
What are the default functions in an empty class.
does the size of empty class depend upon the compiler or hardware(32 bit or 64 bit)?
You are given with space of binary codewords, and you have to come up with an algo to generate all subspace of size 2^1 , 2^2 ,2^3 . . .2^n of that set.
subspace is defined as:
1. it should have the 00..000 code word.
2. it should satisfy closure property. ie if we add any 2 codewords then result shud lie in the subspace.
Note: code words are to be added simply under modulo 2. no concept of carry is there.
ie. 1111 + 1010 = 0101
given an array A[0-n], find the combination of A[i] and A[j] such that
1) A[j] - A[i] is max
2) A[j] > A[i]
and
3) j > i
please suggest a better solution than n-square.
Reverse words in a sentence.
Ex:
Input: "reverse the word"
Output: "word the reverse"
How can you implement queue?
I told him about list, array, stack implementation of queue.
Find the most frequently occurring element in a BST. In this BST we can have leftnode<=rootnode<=rightnode.
//Q. Write an algorithm that will take two dates and tell you if they are more than a month apart, less than a month apart or exactly a month apart.
1. What is difference between override and overload
2. abstract. when will u use abstract
3. what is an interface
4. what is difference betwwen array and link list
5. what is a tree
6. what is a map\dictionary
7. Explain (orally) how would you implement a dictionary via a tree
There are different buildings in one environment, each with machines that can handle one request at a time. How would you design the request handling so that there is no single fail-point and is scalable.
Hint: It is ok if a request is sent to a machine that is already servicing another request. We can handle requests that come back from a machine. But he didnot want a lock on a single file that contained the data of empty machines
Follow up question was, lets say BLDG-A has 250 free machines, BLDG-B has 500 free machines, BLDG-C has 100 free machines and BLDG-D has 0. How would you assign requests? What if you had 850 requests at the same time? Why would you assign what you did?
Given a set of array of size n, return all possible subset of size k.
example: if arr = { 1,2,3,4,5,6} , k=2;
return result is: {1,2};{1,3};{1,4};{2,3};{2,4};{3,4}
or a single array {1,2,1,3,1,4,2,3,2,4,3,4}
You have two sorted list A and B.
A = [1, 3, 4, 6,8,10, 17, 34]
B = [2, 8, 17, 33, 44, 66, 89, 100, 123]
Write a program to print those numbers which are
1) in A and not in B
2) in B and not in A
Eg: After print: 1 , 3 , 4 , 6 , 10, 33, 34, 44,, 66, 89, 100, 123
I was asked to write this in JAVA.
The minimum number of comparisons required to determine if an integer appears more than n/2 times in a sorted array of n integers is ??
a) theta(n) b) theta(log n) c) theta(log*n) d) theta(1)
If an N X N matrix is given, print it in spiral order.
Example: Below is 5 X 5 matrix
i l o v e
d i n t e
n i e e p
a v w r i
m a x e c
Print in spiral order. Output is iloveepicexamandinterview
how many elements can be sorted in theta(log n) time using heap sort ?
Write code for api printInt(int n) assume you have putch(char ch) available to you. Don't use standard library.
When is that we we want to use "user virtual address" instead of "kernel virtual address"? List some situations when we cannot go with kernel virtual address.
Given a sequence of non-negative integers find a subsequence of length 3 having maximum product with the numbers of the subsequence being in ascending order.
Example:
Input: 6 7 8 1 2 3 9 10
Ouput: 8 9 10
There is a SRT file having timestamp and dialogue .
eg . hh:mm:ss , dialogue .
Suppose the movie runs ahead of dialogue . How or what will the approach to make it equivalent with the movie running .
For eg : The movie time is 02: 58:59 and the dialogue is 5 sec delayed.
There are 10 balls .Determine the faulty ball in minimum steps
Special Property Numbers:
Eg--> You have a number 8987656 or 4565676
The difference between consecutive numbers is either 1 or -1.
You are given a range, you need to print the numbers with this special property.
This is on Additive Number Property
Additive Number examples:
123459 (1+2=3, 4+5=9)
314538 (3+1=4, 5+3=8)
122436 (12+24=36)
You are given a range, you need to print all the additive numbers.
You are given a 2-D array with same number of rows and columns. You have to determine the longest snake in the array. The property to find the snake is the difference between the adjacent(left, right, up or down) should be either 1 or -1. If there are more than one snakes with maximum length, the output should print both of them.
Example-->
The given array elements are as follows:
4 7 9 8
5 6 5 4
6 7 8 5
10 9 7 6
The longest snakes are 7->6->5->4->5->6 and 7->6->7->6->5->4
Share market. Given an price of share in order of day as integer array, find out when an user can buy n when he/she can sell to gain maximum profit.
ex : 30, 12, 15, 10, 40, 30, 60, 100,
out put : 10 and 100
30, 12, 15, 10, 40, 30, 60, 100, 2, 110,
out put : 2, 110
30, 12, 15, 5, 40, 30, 60, 130, 2, 110
output: 5, 130
What all design pattern you know. I said i know only singleton.
They asked me to explain Singleton design pattern.
What are wait, notify and notifyAll methods?
Explain one scenario where do you use these methods?
Validating curly braces in java.
Implement a lift. They asked me to tell the logic.
Reversing a character array.
Steps:
1. Take two ref one will referring to start index n one to end index.
2. Swap characters at both indexes
3. Increment start index, decrement end index.
4. Repeat steps 2 and 3 untill u start index < end index
Complexity of this algorithm? IS there an algorithm using which we can achieve complexity of n/2?
How subString works in String class.
subString will not create new string. Class string is having offset and count integers to point to begin index and number of characters.
subString will set these offset and count.
Explain equlas & hashcode methods. When you will override these two methods?
This same question was asked in other two face to face interviews also. You should know how HashMap actually works. Like collision, put, get.
How to increase HashMap performance.
Implement Iterator for integer array.
Write a function which returns kth element from the tail in a linked list.
Implement Iterator class with peek() functionality in Java.
When you enter website what is the communication you see on FIDDLER. The request responses.
Class and Data Structure Design for a "metric" system to determine the top song of a band. Two Web Service calls:
void play(String bandname, String songname);
String topSong(String bandname);
CONSTRAINTS: For this exercise we should constrain the design to a single server and do NOT use a database, but in memory data structure.
SAMPLE INPUT/OUTPUT
play("Guns N Roses", "Welcome To the Jungle");
topSong("Guns N Roses") => "Welcome To the Jungle"
play("Guns N Roses", "Sweet Child of Mine");
topSong("Guns N Roses") => "Welcome To the Jungle"
play("Guns N Roses", "Sweet Child of Mine");
topSong("Guns N Roses") => "Sweet Child of Mine"
scale the architecture
Given a BST and two values a and b, write a method which returns number of nodes in this tree such that a < node value < b
How do you test a spoon?
How do you test a pen?
Where is primitive data stored in java memory?
You are given a graph and an algorithm that can find the shortest path b/w any two nodes
Now you have to find the second shortest path between same two nodes.
In a grid, you are given a position, and every location has some value. find the shortest length so that you can touch to any boundary of the grid. I code it then she asked me to optimize it, I did that also.
You have a binary tree on client machine, how will u send this info to server and how will you again maintain the tree over the server. I thought few mins, tell him my approach, he was asking for easier way. Then finally I told him my approach. He was satisfied and told me to write the code how and what info will u send and how will u again maintain it on the server, I write both the codes and He was very satisfied with my code.
You have a robot in a grid, it can move in forward direction and can change its facing towards north, south, east n west and you are given a command sequence. So what will be the final position of the robot
Example
Grid(100*500)
Robot Position – (5,3)
Sequence — {N,S,M,M,E,W,E,S,M,S,M} North, East, West, South, Move forward
find a pattern in byte array and change that pattern in place (do not use temp array or variable)
for example, find pattern 0,0,3 in an byte array and replace it with 0,0
should be o(n)
my solutions :
Byte*remPattern003(byte arr[] , int &size) //size is input and output variable ///outputs size of output array
{
int k = 0;
for(int i=0;i<size;)
{
if(arr[i] == 0 && arr[i+1] == 0 && arr[i+2] == 3)
{
arr[k++]=arr[i];
arr[k++]=arr[i+1];
arr[k]=arr[i+3];
i+=3;
}
else
arr[k++]=arr[i++];
}
size= k;
return arr;
}Design a Text Editor, in term of class diagram and data structure required to store the data/text and Insert, Delete, search in both direction and Edit operation. Calculate the time complexity for all operation.
Note: the size of file is huge and we don't have the RAM to load entire file into a memory.
Design a Cache System, with the appropriate data structure and operation with the time complexity.
Given an array find the next greatest element to the right of it. [4, 5, 2, 25]
Element NextGreatestElement
4 --> 5
5 --> 25
2 --> 25
25 --> -1
i gave o(n^2), but was
asked to solve in o(n)..You can take extra space...
I was given a space of binary codewords containing 2^k codewords of word length n. And I was asked to generate all possible subspace of size 2^1, 2^2, 2^3 . . . . .,2^k.
Definition of subspace: It should have zero codeword, and it should satisfy additive closure property under modulo 2.
example: say given space of codeword is {0000,0001,1110,1111}. Then subspace of size 2^1 are D1{0000,0001} , D2{0000,1110}, D3{0000,1111}. and subspace of size 2^2 is {0000,0001,1110,1111}.
note: the additive closure is checked under modulo 2. ie. example1 1100 + 1010 = 0110 example2 111100 + 111111 = 000011
(no concert of carry was there, bits are added and modulo 2 is taken)
Binary tree level order traversal with each level is print on different line. i gave the solution by calling print fucntion for each level. but i got stuck in derive the time complexity analysis . pls tell me time complexity ananlysis
You have k lists of sorted integers. Find the smallest range that includes at least one number from each of the k lists.
For example,
List 1: [4, 10, 15, 24, 26]
List 2: [0, 9, 12, 20]
List 3: [5, 18, 22, 30]
The smallest range here would be [20, 24] as it contains 24 from list 1, 20 from list 2, and 22 from list 3.
Given an array, find all unique three-member subsets, with unique being that [0,2,3] and [3,2,0] are the same set. Should run in faster than 2^n time
Data for various stocks is coming from various stock exchange continuously. Which data structure is suitable to store these data? Later I was told that if stocks are unique means only one data is there for each stock, then which data structure would you be choosing?
There is large set of sorted data where number of data is not known. How could a given number be find efficiently?
Write a method that can sort an array of items that can be compared with each others.
Design and code a way to suggest predictions for your query as you type in real time (such as Google Instant).
Design and code a way that Facebook could use to suggest new friends you might know.
Given an array of integers, find Pythagorean triplets.
i.e. find a,b and c which satisfies a^2 + b^2 = c^2
Integers could be positive or negative.
Given a Directed graph, and a source point say S, and say C is the most distant node from S, you need to find the route from S to C . Suppose ,for example there is a path from A-> B- >C, and a path from A->B->D->C, here the most distant node is C with path length as 4. Also, each edge has unit length. Since the graph is directed , you need to implement an algo which takes care of the cycles in the graph. How would you implement this?
What is the difference between a computers heap and it's stack?
what will be the output of the following program and why...
#include<conio.h>
#include<stdio.h>
void main()
{
int a=10,b=20,diff;
diff=&a-&b;
printf("Difference=%d",diff);
float a1=10.0,b1=20.0;
diff=&a1-&b1;
printf("\nDifference=%d",diff);
char a2='a',b2='z';
diff=&a2-&b2;
printf("\nDifference=%d",diff);
double a3=10.0,b3=20.0;
diff=&a3-&b3;
printf("\nDifference=%d",diff);
getch();
}Given a string, you need to find super string by word match. i.e. all words in the input string has to occure in any order in output string.
e.g. given data set:
"string search"
"java string search"
"manual c++ string search equals"
"java search code"
"c++ java code search"
...
input: "java search"
output:
1) "java string search"
2) "java search code"
3) "c++ java code search"
input: "c++ search"
output:
1) "manual c++ string search equals"
2) "c++ java code search"
There are millions of records in given data set and you need to process few million as input.
Design and code static simulator for all gates .i.e. AND / OR / XOR etc.
Where the simulator has to work properly not only for the binary digit but also for the algebraic inputs (i.e doubles as a input type.)
Is this code working fine ? if yes/no give reason ?
#include<iostream>
using namespace std;
struct node
{
int a;
int b;
};
typedef struct node Node;
void swap(void *a,void *b)
{
void *temp;
temp=a;
a=b;
b=temp;
}
int main()
{
Node *a1,*b1;
a1=(Node*)malloc(sizeof(Node));
b1=(Node*)malloc(sizeof(Node));
a1->a=10;
a1->b=20;
b1->a=30;
b1->b=40;
cout<<a1->a<<" "<<a1->b<<endl;
cout<<b1->a<<" "<<b1->b<<endl;
swap(a1,b1);
cout<<a1->a<<" "<<a1->b<<endl;
cout<<b1->a<<" "<<b1->b;
}
I surprised to see the ans after compiling this code ... i think u enjoy this code... :)
3 Baskets, with label Apple Orange and Mixed. All the lables are incorrect. Pick up one fruit from one of the 3 baskets and find the correct labels for these 3 baskets.
How to find a missing value in an size N unsorted array (value from 0 to N but missing one of them).
Difference between C++ and Java
there is a log file which contains info in below format:
timestamp : customer-id : page-id
repeat customers are customers who return to the amazon site(any page) after at least a day.
write a code to print all the repeat customers
Consider a city (visualize a circle). It has n petrol stations in it. You are given the maximum amount of petrol that can be filled at each of these stations. You are also given the distance between one station to the next one. The aim is to cover the entire city and come back to the start point. Assume that 1 liter of petrol will last for 1km.
Q: List out all the possible petrol stations from where the journey can be started, so as to cover the city.
You are given an integer array, where all numbers except for TWO numbers appear even number of times.
Q: Find out the two numbers which appear odd number of times.
How do we design a class.forName("CLASS") , kind of function?
Where the function will accept a string (as a Class Name) as a parameter and accordingly convert it into the subsequent CLASS object.
int board[8][8] each value in the matrix represents a character. 1-9 number represents all whites and 11-19 represents all blacks.
Given a pawn at (x,y) print all possible moves. Assume whites are index 0 and blacks are at index 7.
The cost of a stock on each day is given in an array, find the max profit that you can make by buying and selling in those days
A = {5, 3, 8, 9, 16}
After one iteration A = {3-5,8-3,9-8,16-9}={-2,5,1,7}
After second iteration A = {5-(-2),1-5,7-1} sum =7+(-4)+6=9
Given an array, return sum after n iterations
You have a dictionary, D, that stores the positions of words in a document by mapping words (strings) to positions in the document (arrays of ints.)
You also have a list of words, L.
Your job is to find the shortest sequence of words in the document that contains all the words in L.
E.g., if the document is "a b a c d x b a", then
D["a"] = [0 2 7]
D["b"] = [1 6]
...
If we are given that L=["a", "c", "x"]
Then we should return the start and end point of the shortest sequence that contains all words in L, which is (2, 5)
...the simple way is O(n^2) where n is the number of words in the document
...the way I came up with is exponential in |L|
...the interviewer had a way that was O(n)
Write a function that finds out if any two numbers within that array add up to a target.
bool addsUp(Array<int> input, int target);Blacklist all the nodes in a B-tree, when viewed from all 4 directions.
in a matrix of certain size given we had few values like
12 45 6
23 4 5 6
3 3 4
4 4 4
wewere suppose to move back all the spaces
There are some exceptions that cannot be caught by try catch. How to catch such exceptions? Can we prevent our program to crash if we are not able to catch such exceptions.
Say there are 3 array lists l1, l2 & l3 of same length. Thress threads accessing three lists. Say T1 -> l1, T2 ->l2 & T3 ->l3. It should print in the order say first element of 1st then first element of 2nd list and then first element of 3rd list. Then second element of 1st then second element of 2nd list and then second element of 3rd list.
A string of characters were given, find the highest occurrence of the character and display it.
input:AJDHURNANDANDJNAUYTRAYAUIA
output: A
XML Flat tree goes like this :
<?xml version="1.0" encoding="utf-8"?>
<?xml-stylesheet type="text/xsl" href="Stack.xsl"?>
<Items>
<Item>
<Id>1</Id>
<ParentId>0</ParentId>
<Name>1</Name>
<SortOrder>0</SortOrder>
</Item>
<Item>
<Id>2</Id>
<ParentId>1</ParentId>
<Name>1.1</Name>
<SortOrder>0</SortOrder>
</Item>
<Item>
<Id>3</Id>
<ParentId>1</ParentId>
<Name>1.2</Name>
<SortOrder>0</SortOrder>
</Item>
<Item>
<Id>4</Id>
<ParentId>1</ParentId>
<Name>1.3</Name>
<SortOrder>0</SortOrder>
</Item>
<Item>
<Id>5</Id>
<ParentId>1</ParentId>
<Name>1.4</Name>
<SortOrder>0</SortOrder>
</Item>
<Item>
<Id>6</Id>
<ParentId>0</ParentId>
<Name>2</Name>
<SortOrder>0</SortOrder>
</Item>
<Item>
<Id>7</Id>
<ParentId>6</ParentId>
<Name>2.1</Name>
<SortOrder>0</SortOrder>
</Item>
<Item>
<Id>8</Id>
<ParentId>6</ParentId>
<Name>2.2</Name>
<SortOrder>0</SortOrder>
</Item>
<Item>
<Id>10</Id>
<ParentId>3</ParentId>
<Name>1.2.1</Name>
<SortOrder>0</SortOrder>
</Item>
</Items>
</XML>and to display the output like below
1
1.1
1.2
1.2.1
1.3
1.4
2
2.1
2.2Assuming the XML parsing is done and now is in some data structure in memory
and write a C or C++ program to display the output as above...
I pressume that interview was expecting which data structure I may use to store
XML elements values and how do I retrieve the same.
I tried using Binary search tree however it needs to have max of 2 children
for each node. again thought of using array, which i thought is a bit
complicated compare to tree..
guess array would be one of the solutions like a[i][j][k]
for(i=0;i<m;i++
{
print (a[i] n );
for (j=0;j<n;j++);
print(a[i][j] n);
for(k=0;k<p;k++)
print(a[i][j][k] n);
}I feel tree would be more efficient way for programming this kind of
problems however I could find other than Binary search tree for programming
this again that is not a solution for this
There is a class
class vehicle
{
int door_numbers;
obj colour;//another class has int members Red, Green,Blue
bool has_ac;
}
there is a huge list of data of vehicles, the number of doors may vary to 1-million (imaginary vehicle :) ).
there may be millions of colors.vehicle may or may not have AC. How would you save this such that any combination
(say all blue cars with ac having 6 doors) may be accessed easily.
Discuss algorithm, complexity and testing strategy
How to check if a binary tree is a binary search tree?
Sort a singly-linked list of unknown size using constant space.
Multithreading - When we use synchronized keyword in java, which synchronization primitive is used exactly? lock, sempahore, monitor, mutex?
Given a double ended queue with front and rear as two pointers, if a two people play a game. Say removal of number from a given list- from either side of the list. given the fact that the players can view the list of numbers, maximize the chance of each player winning?
I was thinking more in terms of minmax tree/ alpha beta pruning. Any suggestions on this?
Any suggestions?
There is a machine A which produces random output either 0 or 1 with 50% probability each. Its output(when run many times, say 2 or 3 times i.e 0 1 1 i.e. binary string of length n) is fed as input to Machine B for which output is again 0 or 1. But B should produce 75% 1's and 25% 0's. Write an algorithm to achieve this.
Find top k searched elements from a continuous stream of data.
find the length of integer array using array pointer and remove the redundant element from the list using pointer ?
Q .2 candles each burns for 1 hr each ,calculate 45 min time
by burning them in one go .
Ans :
burn the first candle from both the side, parallel to first one , burn the other from single side only, once the first is burnt completely 30 mins are over and second is already half burned .
now start burning the second one from the other side .
you have 45 mins calculated.
!!! Bam !! again kid stuff !!
Remove duplicates from an array say {1,2,7, 9, 9, 5, 4, 9} and create a new array and put the values in the new array. Note: Not to use any collection classes. Space and time complexity needs to be considered.
what is the probability of 5 people with different ages sitting in ascending or descending order at a round table.
waf to rotate array by k unit
size of array n=6
1 2 3 4 5 6
k=2
output
5 6 1 2 3 4
find the next greatest number that can be form by same digit of the given number ..
sample test case
input
4765
output
5467
waf to swap kth node from first with kth node form last ..
example
if k=3
link list input
1->2->3->4->5->6->7.
output linked list
1->2->5->4->3->6->7
given 4 points, whose x and y coordinates are both integers. they are all different. write a function to check if they form a square.
i forgot to point out that the points can be given in any order
wap to find the longest arithmetic sequence in given array... return number of element in seriese...
simple test case..
sizeofarray=4
array element
3 4 5 8
output
3
sample test case
size of array =10
array element..
-1 1 3 7 11 15 19 20 21 22
output
5
waf for a linked listed ..
shift all digit to first then consonant then vowel ..
such that list contain only one time one digit , consonant , vowel ..
List *(List *head);
input :
2->a->5->a->2->b->o->n->5->n.
output..
2->5->b->n->a->o..
wap to take one rotate a square matrix anticlock wise by 90 degree and add a particuler number after rotation to each prime column.
function prototype should be..
void rotate(int a[][],int size, int keytobeadded);...
sample test case....
input
size=3
keytobeadded=5;
square matrix :
1 2 3
4 5 6
7 8 9
output should be
3 11 9
2 10 8
1 9 7...........
Write a program that outputs all possible strings formed by using the characters 'c', 'a', 'r', ' b', ' o', and 'n' exactly once. Also write complexity.
people are asked to dress in blue and green for a party. People who come in blue colour are assigned "1" and people who come in green are assigned "2". So the sequence would be something like 121111222212121212....
Now we need to split the group in x subgroups where the size of each subgroup can take values from given set [3,4,5,6....] and all the members of the group should be in some subgroup. however the ordering of the group should be intact(cannot switch positions). write algorithm/code which splits the group into the required x subgroups where the sum of squares of the differences of 1's and 2's in each sub group is a minimum.
Replace bit n to bit m of an integer 'a' with bit n to bit m from another integer 'b'.
e.g. a = 00000000 00000000 10101010 00110011
b = 1111111 11110000 10010011 00000001
n = 9, m = 16
Answer : a = 00000000 00000000 10010011 00110011
In an interview I was asked a question on strings. The problem is given a string s1= "ABCDBCCDABCD". and a pattern "BC". we have to replace this pattern with other string ("UVW" or "U"or "uv"). Do this without creating new string.
Take the case to replace "BC" with following
a) "uvw" s1=AUVWDUVWCDAUVWD .
b) "U" s1=AUDUCDAUD .
c) "UV" s1=AUVDUVCDAUVD .
This was my first question and I was stuck on this. :(
user inputs values which must be stored. The duplicates must be ignored without scanning the array/list. is there a method to do this?
Write an efficient function that returns the n’th Fibonacci number (There are many ways to solve this problem. Please write the most efficient method possible). Each Fibonacci number is the sum of the last two. The first 10 are: 1, 1, 2, 3, 5, 8, 13, 21, 34, 55.
long getNthFibonacci(long i) { ... }
Setup:
Assume primitive Facebook. FB has Members.
class Member {
String name;
String email;
List<Member> friends;
}
Question:
Code printSocialGraph(Member m). Direct friends of m are Level 1 friends. Friends of friends are level 2 friends.....and so on
Print level 1 friends first. Then print level 2 friends....and so on
void printfriendsByLevel(Member m){
//Your code here
}
Let's say we're developing a vector graphics application. It will allow the user to create lines, rectangles, circles, text, etc. and manipulate them independently - move them, resize them, etc. Design an object model for this application. (How would you model the representation of the document in an object oriented language? What classes would you define? What methods would you have? What would your API look like?)
write a function that print TRUE if (){}[] are balanced in expression .. otherwise return FALSE.
[{()}] currect.. priority of [ >}>)..........it should be preserved
....................................................................................
void check(char *a)
{
struct s
{
char ch;
s*next;
};
s *st=NULL;
s*node=NULL;
if(a=='\0')
{
cout<<"TRUE";
return ;
}
else
{
while(a[0]!='\0')
{
{
node=(s*)malloc(sizeof(s));
char c=a[0];
switch(c)
{
case '[':
if(st==NULL)
{
node->ch=c;
node->next=NULL;
st=node;
a++;
}
else
{
if(st->ch=='('||st->ch=='{')
{
cout<<"FALSE";
return ;
}
else
{
node->ch=c;
node->next=st;
st=node;
a++;
}
}
break;
case '{':
if(st==NULL)
{
node->ch=c;
node->next=NULL;
st=node;
a++;
}
else
{
if(st->ch=='(')
{
cout<<"FALSE";
return ;
}
else
{
node->ch=c;
node->next=st;
st=node;
a++;
}
}
break;
case '(':
if(st==NULL)
{
node->ch=c;
node->next=NULL;
st=node;
a++;
}
else
{
node->ch=c;
node->next=st;
st=node;
a++;
}
break;
case ')':
if(st==NULL||st->ch=='{'||st->ch=='[')
{
cout<<"FALSE";
return ;
}
else
{
if(st->ch=='(')
{
s *newnode=st;
st=st->next;
free(newnode);
a++;
}
}
break;
case '}':
if(st==NULL||st->ch=='('||st->ch=='[')
{
cout<<"FALSE";
return ;
}
else
{
if(st->ch=='{')
{
s *newnode=st;
st=st->next;
free(newnode);
a++;
}
}
break;
case ']':
if(st==NULL||st->ch=='{'||st->ch=='(')
{
cout<<"FALSE";
return ;
}
else
{
if(st->ch=='[')
{
s *newnode=st;
st=st->next;
free(newnode);
a++;
}
}
break;
default :
a++;
if(a[0]=='\0')
{
cout<<"TRUE";
return ;
}
break;
}
}
}
if(st==NULL&&a[0]=='\0')
{
cout<<"TRUE";
return ;
}
if(st!=NULL)
{
cout<<"\nFALSE";
return ;
}
}
}
write a funtion to shift all vowel in first and all consonant in last . Order of all vowel and consonant should should preserved .
You are given the task of creating the address book application for a smart phone. There are some
of the top level features you must implement.
1.There will be 1000+ phone book entries and user must get very quick response.
2.On default screen it shows the names of all people in alphabetical ascending order.
3.Using the search option, user can search and it will show only those names starting
with those characters which are typed in the search box.
You are supposed to compare two different data structures and list down the pros and cons of each
and finally recommend the best suited data structure.
Highly coupled code is code where the dependencies between classes are dense, lots of things
depend on other things. This kind of program is hard to understand, tough to maintain, and tends
to be fragile, breaking easily when things change.
Simplistically, we can say that class A is statically coupled to class B if the compiler needs the
definition of B in order to compile class A. Moreover dependencies among them are transitive.
That is if A depends on B and B depends on C, then A also depends on C
Create a program logic/pseudo code which can print the "expanded dependency tree" given a set
of input per class dependencies. Make sure that there are no duplicates in the output
Input
A -> B,C
B->C,E
C->G
D->A,F
E->F
F->H
Output
A depends on B C E F G H
B depends on C E F G H
C depends on G
D depends on A B C E F G H
E depends on F H
F depends on H
Given an virtual 4x4 boggle board, and some 4 letter words, determine if the words are in the board
ex.
S M E F
R A T D
L O N I
K A F B
STAR- no
TONE- no
NOTE- yes
SAND- yes
etc.
1)Given binary tree find the min weighted node. ?
Min weighted node is one which has minimun sum,where sum = Rootnode.getdata + leftnode.data + rightnode.data.
implement the method to achieve the above,,,
how would u implement a function tat would generate x object 20% of the time , y object 10% of the time,z object 70% of the time?
Which data structure would u use to pass this information to the function from the main.?
What is deque ? - double ended queue
Which data structures would u use to implement deque ?
Complexities of each data structure?
Implement it using array such tat all the operations are O(1).
operations are - insert at beginning,insert at end, delete at beginning ,delete at end.
How would u achieve this.?
Write interface and code to do the above.?
Given an array of N positive integers, N being even, and a number K, find out if it is possible
to form pairs of the numbers present in the array such that the sum of numbers in each pair is
divisible by K.
Alice and Bob are playing a game. The game is played as follows :
- There are N piles of coins on the table. Pile i has A[i] coins.
- In each turn, each player can pick up 1 or more coins from the leftmost non-empty pile.
- If a player picks up a coin from pile i , all coins from piles 0 to i-1 should have been taken.
- The person who picks up the last coin loses the game.
Alice and Bob play the game alternately. Alice plays first. Given the number of piles N and the
number of coins Ai in pile i, you have to determine which player will win the game, assuming
both play optimally.
Write a method to evaluate if a given integer is prime.
How will we find given binary tree is binary search tree or not with complexity less than O(n)
How to find out if a linked list is circular?
(Apart from the straightforward way of going through all nodes and comparing with Head)
Given a number, return the next multiple of 64 that follows it, using bit operations and no loops.
e.g input = 90, return 128.
How to find out the minimum element in a stack(of integers)?
You can modify the pop/push operations.
Design a data structure to store names and phone numbers in mobile phone. Implement methods to insert and to get phone number .
You are trying to to daemonize an unknown, black-box binary executable. The binary executable returns no output to STDOUT or STDERR. Assume that the mystery binary return code is non-zero. What troubleshooting steps might you take to learn more about what the binary is supposed to do, and why it is failing?
During boot, after the BIOS performs a successful power-on-self-test, describe everything that occurs until the console is presented to the user.
5. There Are N Coins On A Table. There Are Two Players A&B. You Can Take 1 Or 2 Coins At A Time. The Person Who Takes The Last Coin Is The Loser. A Always Starts First.
1. If N=7, Then
A) A Can Always Win By Taking Two Coins In His First Chance.
B) B Can Win Only If A Takes Two Coins In His First Chance.
C) B Can Always Win By Proper Play.
D) None of the Above.
2. A Can Win By Proper Play If N Is Equal To
A) 13 B) 37 C) 22 D) 34 E) 48
3. B Can Win By Proper Play If N Is Equal To
A) 25 B) 26 C) 32 D) 41 E) None
4. If N<4, Can A Win by Proper Play Always?Answer: Yes.
I was asked to explain memento pattern.I explained with this example.
class Originator:ICloneable
{
public string a;
public int b;
public object Clone()
{
Originator o = new Originator();
o.a = this.a;
o.b = this.b;
return o;
}
}
class CareTaker
{
List<Originator> l = new List<Originator>();
public void SaveMemento(Originator o)
{
l.Add((Originator)o.Clone());
}
public Originator RetrieveMemento(int i)
{
return l[i];
}
}
class Program
{
static void Main(string[] args)
{
CareTaker c = new CareTaker();
Originator o = new Originator();
c.SaveMemento(o);
}
}The interviewer said this is is different from memto pattern ... can anyone explain where the difference is!!!
Given a file using regex find all the ip address ina text file.
Given a string , " This is a test" reverse it: " tset a si siht"
Do this recursively.
Difference betwen Aggregation and composition. What is enum. Write a design pattern except singleton. Write binary search. Write recursive binary search. Elaborate on man in middle attack. How you create a branch - why in svn? . Explain the architecture of your previous work experience. explain thread concept of synchronization.
Some numbers on phone keypad can represent several characters(such as 2-'A','B','C'). Design an algorithm to return a list of all vocabularies which represented by several numbers. You can implement the dictionary yourself.
Sample input: 227
output: car, bar, cap
The interviewer said he could solve it by O(1).
Someone know the answer?
Sorry for my poor English.
Design the Facebook newsfeed for an Android app. The actual design would be very complex so you may limit your solution to only status updates and photo posts. Keep your answer broad rather than deep since it would need to fit in a 45-minute interview.
Normally you would need to ask the interviewer a lot of questions but since that is not possible here, state your assumptions.
Write a function that accepts two or more strings and returns the longest common substring in all of them.
Write a function that takes a string and returns true if the entire string is a palindrome, otherwise return false. The function should be case-insensitive and ignore any whitespace or punctuation.
For example, return true for:
"A man, a plan, a canal: Panama."
Implement this Java function:
int findNeedleInHaystack(String haystack, String needle)
If needle is a substring of haystack, it should return the index of needle.
Given a char array {1,234,34,54}
Modify the char array so that there is no comma in the most efficient way. We must get a char array {12343454}
Given an unsorted set of numbers from 1 to 10 with one number missing .
How to find the missing number in the set without sorting. How to find if two numbers are missing in the set?
Given 2 arrays with numbers, multiply the numbers with corresponding indexes and return the sum of all the products.
Twist :- When one array gets consumed then start with its first element again.
A : 1,2,3,4,5
B : 2,1
Output: 24 (1*2 + 2*1 + 3*2 + 4*1 + 5*2)
Print N numbers of form 2^i.5^j in increasing order for all i >= 0 , j >= 0 ?
Example : - 1,2,4,5,8,10,16,20.....
You have some geometrical forms (tetris like) and you need to integrate them all into a square. Find an algorithm for it
Goal: Create a software application that takes a set of people-relationships as input and provides a user interface that allows an operator to determine how “connected” any two people are.
Relationships / Input:
John:Jane:Jill:Jeb:Jim
Jane:John:Jason:June
Jill:John:Jim
Jim:John:Jill:June
Jeb:June:John
June:Jim:Jane:Jeb
Jason:Jane
For example, John has a 2nd degree connection to June since June has a 1st degree connection to Jim who in turn has a 1st degree connection to John.
Given a set of consecutive integersA[1....n] and an integer value x,y, need to find the list of subset of integers in A[1....n] which has x integers and sums up to y.
Say A = [10,11,12,13,14,15,16,17,18,19,20], X = 4 and Y = 55,
it should give the values of (10,14,15,16),(10,11,15,19),(10,11,16,18),(10,12,16,17) and so on..
Write an algorithm to find all the subsets.
How do you make sure an API does not leak memory?
Is there any difference between the usage of void pointer and unsigned int ? if yes what the advantage of one over other?
Guys I havn't thought guys commenting here are idiots as well. so please read the detail explanation for it in my below comment. :)
from given array of n elements find the maximum element for each consecutive sub-array of k elements.
eg.
array=[6,5,4,3,2,1]
k=3
ans=6 5 4 3
explanation:-
6 from array [6,5,4]
5 from array[5,4,3]
Write a program to find the element in an array that is repeated more than half number of times. Return -1 if no such element is found.
Write a program in C to read all the characters from standard input and output the reverse when the user presses enter key.
Write a program in C to do run length encoding of an string in place. Desired space complexity O(1).
n*n matrix, find the longest ways for each players.
players: red and blue.
players can jump to the next position based on the opposite player, after jump, remove the opposite player.
An updated tic tac toe game: n*n matrix, two users: X and O. If 3 respective marks together(no mater: vertical, horizontal, diagonal ) will win 1 point; For user X, 6 respective marks together will win 3 points; For user O, 8 respective marks together will win 6 points, check who win.
Had a phone interview with Bloomberg.
Asked about my projects and my contribution to each of them. How to sort numbers between 1 and 10000. How will you sort if there are 10000 numbers between 1 and 50000. Which sort do you prefer for linked list and array list. Again asked about my projects. Any questions? done with the phone interview. No Coding part.
Write test cases for removing the given chars from a string.
Design LRU in C++
Design Garbage Collector in C++.
Design a Tic Tac Toe Game. Classes Segregation and Code Flow.
A transaction involves transferring amount from one account to another account.There is one queue being populated with transaction requests . Use 4 threads to process requests. Ensure data consistency and fastest way to process the requests .
Given:
1. request will contain fromAccount, toAccount, amount 2. list of n account which are involved in transactions.
Question from my friend's interview.
Problem statement : How would you design a logging system for something like Google , you should be able to query for the number of times a URL was opened within two time frames.
i/p : start_time , end_time , URL1
o/p : number of times URL1 was opened between start and end time.
Some specs : Database is not an optimal solution A URL might have been opened multiple times for given time stamp. A URL might have been opened a large number of times within two time stamps. start_time and end_time can be a month apart. time could be granular to a second.
In a game, you bet using the following strategy. Whenever you lose a bet, you double the value of the bet for the next round. Whenever you win, the bet for the next round will be one dollar. You start the round by betting one dollar.
For example, if you start with 20 dollars, and you win the bet in the first round, lose the bet in the next two rounds and then win the bet in the fourth round, you will end up with 20+1-1-2+4 = 22 dollars.
You are expected to complete the function, getFinalAmount, which takes two arguments. The first argument is an integer initialAmount which is the initial money we amount we have when we start the betting. The second argument is a string betResultsThe ith character of outcome will be either 'W' (win) or 'L' (lose), denoting the result of the ith round.
Your function should return the amount of money you will have after all the rounds are played. If at some point you don't have enough money in your account to cover the value of the bet, you must stop and return the sum you have at that point.
Sample Test Cases:
Input #00:
12
WWWWWWWW
Output #00:
20
Explanation:
The initial amount is 12, for every win, you gain 1 dollar.
There are totally 8 consecutive wins and no losses, hence total money gained = 12 + 8 = 20
Input #01:
15
LLLWLLLL
Output #01:
1
Explanation:
The initial amount is 15. As stated in the problem, the amount of bet doubles for every loss.
1st round - Loss: 15-1 = 14
2nd round - Loss: 14-2 = 12 (Bet doubles)
3rd round - Loss: 12-4 = 8
4th round - Win: 8 + 8 = 16
5th round - Loss:16-1 = 15 (Since the previous bet was a win, this bet has a value of 1 dollar)
6th round - Loss: 15-2 = 13
7th round - Loss: 13-4 = 9
8th round - Loss: 9-8 = 1
Complete the function getEqualSumSubstring, which takes a single argument. The single argument is a string s, which contains only non-zero digits.
This function should print the length of longest contiguous substring of s, such that the length of the substring is 2*N digits (maximum length of the string is 49) and the sum of the leftmost N digits is equal to the sum of the rightmost N digits.If there is no such string, your function should print 0.
Sample Test Cases:
Input #00:
123231
Output #00:
6
Explanation:
1 + 2 + 3 = 2 + 3 + 1.
The length of the longest substring = 6 where the sum of 1st half = 2nd half
Input #01:
986561517416921217551395112859219257312
Output #01:
36
rints the highest possible numberthat a user can print.
Length is given as input.Print all possible permutations of numbers between 0-9.
Eg: if input length=4
all possible combinations can be 0123, 1234, 5678,9864,...etc all combinations of length from in all numbers between 0-9
Suppose you reach your home and noticed that the light bulb in your corridor is not working. What will you do in such a situation?
In a series of 1 to N, two numbers are missing. Find the missing numbers? Quickest way?
write a program to Generating Random Integer numbers without repetition ??
Coding:
Public void TransferAccount(AccountID id1, AccountID id2){
Account a1 = id1.GetAccount();
Account a2 = id2.GetAccount();
//Swap amounts.
Temp = a1.Balance;
a1.Balance = a2.Balance;
a2.Balance = Temp;
}Q1: How do you make it thread safe?
I said use “public void synchronized” Good. But terrible performance since the entire method is synchronized.
Q2: Can you not lock on the entire method? I said used nested locks:
Synchonized(a1)
Synchronized(a2)
{
//swap
}His q: This will lead to a deadlock if in another thread I call Transfer (id2, id1) and Transfer (id1, id2).
Synchonized(a1)
Synchronized(a2)
{
//swap
}Synchonized(a2)
Synchronized(a1)
{
//swap
}How do you prevent this then? How do you design your code to not to get in to deadlock? (stumbled here)
How do you detect deadlocks? What tools would you use? I said do “Kill -3 .<process id>, and analyse if anything is deadlocked.
3) Coding question:
public class ThreadingQuestion extends Thread
{
public static void main(String[] args) {
public static boolean flagRun = true;
new thread {
void run(){
while (flagRun)
//do something
}.start()
flagRun = false;
}Will the thread spawned will ever see the flagRun=false?
My corrected answer after a couple of attempts: No, since each thread will get a copy of it’s own flagRun, changing the flagRun value in the main thread will not be seen in the spawned thread.
How to fix it: declare flagRun to be volatile so that the values can be changed and seen in either threads.
What is difference between "volatile" and "static volatile"? Give an example
Explain what is “static synchronized?” What does it lock on? what is ‘synchronized’? what does it lock on?
Coding: Write a Client/Server. Three methods are given. Msg.Get(), Msg.Process(), Msg.Send(). Write code. Since Msg.Get() and Msg.Send() has to send messages over the network. It takes a lot more number of threads. So how many threads out of 10, would allocate to each of the three processes. What is the proportion?
Puzzle: There are 5 slots(1,2,3,4,5) and 5 people(A,B,C,D,E). Each of them provide their preferences. A=1, B=2, C=3, D=4, C=4. Given an arbitary starting sequence say BCDEA, going clock wise: how many passes does it take to fill in those slots so that max number of people are happy. People are happy if A gets 1, B gets 2, C gets 3, etc. Remember D and E cannot be kept happy together at the same time because both of them prefer Slot-4.
My answer: Worst case scenario when you start at BCDEA(only E is happy because E comes in 4th position and prefers 4), next rotation pass CDEAB(no one is happy), DEABC(no one), EABCD(no one), ABCDE(4 people are happy). So for N people, it takes N passes.
His question: Can you do better than N passes? (Can you do this in less than N passes?)
(I tried to come up with something but stumbled.)
Code up a simple Bloom Filter for four letter words. Assume all words are lowercase, exactly four letters long, and only use the letters a to z. An example set of test words might be able, band, bend, card, darn, form, grab, harm, look, make, mate, peer, and team, but assume the actual list of words is much bigger.
given an int array with no duplicate numbers, write a function to return number of ways to calculate a target number.
example: given {2,4,6,8} Target = 12
2 + 4 + 6 = 12,
4 + 8 = 12,
6 + 8 - 2 = 12,
2 - 4 + 6 + 8 = 12,
return 4
difference between hashtable and hashmap in C#?
when to use hashtable, list, hashmap and dictionary.
Given an array find any three numbers which sum to zero. Give the best algorithm.
Given an array of both positive and negative numbers, find the contiguous range in the array which gives the maximum product. Give an algorithm which runs in O(N).
Given a number, print its corresponding string representation. Example: I/P: 523, O/P: Five hundred and twenty three, I/P: 501, O/P: Five hundred and one, I/P: 11, O/P: eleven
In browsers caching of web links that a user clicks is done.
The recent url that user clicks on should come to the top of the list.
How to implement hash table for it?
If there is a million data in file(assume integers).
The memory is enough to hold all the data.
After loading all the data into data structure , we need to insert 500 new integers after the 10000th element.
What Data structure to use and how to use?
Which one is faster and why?
1. Array
2. Link List.
If we just want to iterate in for loop and print it.
Each time a visitor requests a page from our website, our webserver writes a log entry recoding the visitor's identity and the kind of page requested. Entries are written in chronological order to a plain-text file, with one entry per line. The format of each entry is:
user-id page-type-id
User IDs are arbitrary strings that uniquely represent a given user; if a user visits multiple pages, each log entry will have the same user ID. Page type IDs are arbitrary strings that uniquely represent a given kind of page on our site, such as the homepage, a product detail pages, or the shopping cart. Tons of users visit our website, but there are only a few dozen types of pages.
We can use our weblogs to answer questions about user behavior. One interesting question is: what is the most common three page sequence through the site? E.g., if the most common pattern is to buy items advertised on the home page of the site, we might see the most common three page sequence as "Homepage -> ProductDetailPage -> ShoppingCart". However, if customers spend a lot of time browsing the "Customers who bought this item also bought" feature, we might see the most common three page sequence as "ProductDetailPage -> ProductDetailPage -> ProductDetailPage".
Attached is a sample log file for your reference. Within the first 10 lines of the sample, customer "234" travels through the sequences "Listmania -> ProductDetail -> Checkout" and "ProductDetail -> Checkout -> HomePage" once each.
For the sake of this test feel free to assume that everything will fit in memory. Do keep in mind that given the size of our data sets, performance has to be considered, also, we will be looking at more than just correct output..
How do you add up a very long list of numbers multiple threads (100 threads?) How many cores do you require?
How do you increase the performance of this program? Does the number of threads created get limited by the cores of the box? How exactly are you gonna delegate it to the cores? (as in- these number of threads need to use core#1, and so)
You are given a dictionary, in the form of a file that contains one word per line. E.g.,
abacus
deltoid
gaff
giraffe
microphone
reef
qar
You are also given a collection of letters. E.g., {a, e, f, f, g, i, r, q}.
The task is to find the longest word in the dictionary that can be spelled with the collection of
letters. For example, the correct answer for the example values above is “giraffe”. (Note that
“reef” is not a possible answer, because the set of letters contains only one “e”.)
You are given a set of integers and you are also allowed to apply sign change operation on all elements. Write an efficient algorithm to find minimum Sum. The minimum Sum should be greater than equal to zero. e.g. if Set is { 2, 1, 3, 4, 2 } Minimum Sum is 0 since you can modify the original set as { -2, -1, -3, 4, 2 }
The input begins with n (the number of integers in the set) followed by n integers. Input ends when n is 0.
For each test case please output the answer in a separate line for each value of n.
Bounds :
0 < n <= 1000
sum of the following n numbers <= 100,000
Write implementation of PIVOT keyword found in SQL server.
How will you store a million phone numbers in a space efficient way?
There are five 10 monster As on the left of the road and 10 monster Bs on the right of the road, the road is with length 21 with a empty slot in the middle. Both A and B can jump over the other type or move forward to a empty slot but cannot move backward.
for example(* means the empty slot), the following movement are allowed:
AA*BB --> AAB*B
AAB*B --> A*BAB
the following movement is not allowed:
AAB*B --> AA*BB
Question:
What is the least number of steps to let them go through the road.
Given the matrix
21 22 23 24 25
20 7 8 9 10
19 6 1 2 11
18 5 4 3 12
17 16 15 14 13the coordinate of 1 is (0, 0), of 2 is (1, 0), of 17 is (-2, -2).
Question:
1) what is the number in the matrix given (x, y);
2) what is the function n(x, y).
Given list of pounds, the pounds that can be measured using a balance should be displayed.
For Ex: 100,250
The output will be 100,250,150
The number of pounds which will be given in input might vary. Can someone please help with an algorithm for this?
We're playing a game. Cards numbered from 1-10 are placed in a hat. whatever card is drawn is the paid out amount. how much should i charge you to play this game? If you can redraw by placing the first card back into the hat, what is the new price?
Assume you daily prices of a stock
3 7 4 10 11 8 5 4 8 yadda yadda
You can only buy 1 share or sell 1 share a day, but you can only sell if you own the stock. You can't hold more than 1 share. write me an algo that finds me the strategy that has the highest pay off.
Don't want the generate all possible strategies and compare.
Input is a number of words. Construct a listing of valid 6-letter words. You have access to bool IsValid(const string& word); Implement Insert() and Get() for this listing.
Given coordinates (X[i],Y[i]) of all the cities in the world(for simplicity lets consider we have 2D world map). You are given a user's location (x,y), find out the closest city to the user. Write code for it.
Update:
Time complexity of the solution should be better than O(n) as there will be multiple lookup queries with different input points.
You can preprocess the data in any way you like, but you need to minimize the query execution time complexity.
There is an old dry well. Its sides are made of concrete rings. Each such ring is one meter high, but the rings can have different (internal) diameters. Nevertheless, all the rings are centered on one another. The well is N meters deep; that is, there are N concrete rings inside it.
You are about to drop M concrete disks into the well. Each disk is one meter thick, and different disks can have different diameters. Once each disk is dropped, it falls down until: * it hits the bottom of the well; * it hits a ring whose internal diameter is smaller then the disk's diameter; or * it hits a previously dropped disk. (Note that if the internal diameter of a ring and the diameter of a disk are equal, then the disk can fall through the ring.)
The disks you are about to drop are ready and you know their diameters, as well as the diameters of all the rings in the well. The question arises: how many of the disks will fit into the well?
Write a function:
class Solution { int falling_disks(int[] A,int[] B); }
that, given two zero-indexed arrays of integers − A, containing the internal diameters of the N rings (in top-down order), and B, containing the diameters of the M disks (in the order they are to be dropped) − returns the number of disks that will fit into the well.
For example, given the following two arrays:
A[0] = 5 B[0] = 2
A[1] = 6 B[1] = 3
A[2] = 4 B[2] = 5
A[3] = 3 B[3] = 2
A[4] = 6 B[4] = 4
A[5] = 2
A[6] = 3
the function should return 4, as all but the last of the disks will fit into the well. The figure shows the situation after dropping four disks.
Assume that:
N is an integer within the range [1..200,000];
M is an integer within the range [1..200,000];
each element of array A is an integer within the range [1..1,000,000,000];
each element of array B is an integer within the range [1..1,000,000,000].
Complexity:
expected worst-case time complexity is O(N);
expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments).
Elements of input arrays can be modified.
Given a sorted array of size N and a sorted array of size M+N, merge the first array into the second preserving order. There is enough space in the second array to hold all elements from the first one.
Given a set of 2D points, some integer k, find the k points closest to the origin, (0,0).
How will you describe iOS manual memory management for a new developer in few words?
How would you implement call for canceling queued blocks with dispatch_after?
Suggest a best data structure which cab be used to represent N-ary tree. Given the root node of the same, write a function which finds out whether or not the tree has a loop/cycle.
Given a binary tree. Write a function that takes only root node as arguement and returns (sum of values at odd height)-(sum of values at even height).
Given a stock prices 20,50,52,10,45,34 and each day the stock price will buy and sold in another n days.Calculate which day the maximum profit will get.
Escape strings. Convert special ASCII characters to form of ‘\ooo’, where ‘ooo’ is oct digit of the corresponding special character.
The ascii characters that smaller than space are regarded as special characters.
An array contains two sub- sorted arrays. Give an inplace algorithm to sort two sub arrays.
for ex: I/P: 1 4 5 7 8 9 2 3 6 10 11
O/P: 1 2 3 4 5 6 7 8 9 10 11
Return a shortest prefix of <code>word</code> that is <em>not</em> a prefix of any word in the <code>list</code>
e.g.
word: cat, it has 4 prefixes: “”, “c”, “ca”, “cat”
list: alpha, beta, cotton, delta, camera
Result is “cat”
Implement memcpy function which accepts num of bits as argument as oppose to number of bytes.
memcpy (src, dst, num_bits)
Arrange 1 to N in random order with no duplication.
Write a program to sort an array of strings so that all anagrams are next to each other
ex
input {god, dog, abc, cab, man}
output {abc, cab, dog, god, man}
What should be the output of the following code.
class Test {
public int i=0;
@Override
public int hashCode() {
return i;
}
}
Class a{
psvm(){
HashMap <Test, String> hm = new HashMap();
Test t1 = new Test();
hm.put(t1,”success”);
sysout(hm.get(t1)); //print success
t1.i = 10;
sysout(hm.get(t1)); //NULL
}
}
Given a array of numbers and a number N. Find out all combinations of 3 numbers in array whose sum is N.
Genarally, there is a common similar problem to find all possible pairs whose sum is given number. Now the problem extention to this. Find all possible 3 numbers whose sum is given number.
Whats the best way to synchronize Singleton class.
How will you synchronize 3rd party library from your application..
Suppose we use binary search tree to implement set, design an algorithm that we can get an random element from the set, while maintain all the other set operations have same complexities.
Suppose we have r lists with integers from 1 to n. The sum of the lengths of the lists is n. The lists can be different lengths and the same integer may appear in more than one list. Sort all the lists in O(n) time.
if u have singleton class n war file and two application are acceing the war file what wil hapeen to that singleton class.....ans - some class loader concepts.
how wil u use the lock mechanism in java
what will happen if u build code on java 16 and put on machine with java 15
Explain exceptions in java..what is base class of exception...what does error class do..what does runtimeexpception class do
Difference between thread and process
Explain how hashtables work internally. How is hashcode generated and what wiill happen to hash code when 2 values are same.
Given an 2D array of characters. Find words in the array (either vertical or horizontal). a character cannot be part of 2 words. Maximize the number of characters used. Hint: 1D variant can be solved by Dynamic programming in linear time.
Find kth Largest element in BST
How can you tell if your system is little endian or big endian?
There is a class called A, which receives co-ordinate (x, y) which is processed in a function called fn(x,y): produces an address in memory, pass that address to B and then B retrieves data from memory at that address and then sends that data back through two 32 byte (total 64 byte) data chunk to users. Design the class. follow up questions: How to improve the functions. What are the main bottlenecks?
there are 5 stairs. you can take either 1 or 2 steps
how many combinations you can take to climb the stairs?
Write a program to find the first occurance of one string into another : it is okay to write a O(n2) algorithm
Write a program to print the powerset.
E.g. given this set {1,2,3}, it will print {},{1},{2},{3},{1,2},{1,3}, {2,3}, {1,2,3}
Write a program to clone a graph
Given an array of 0s and 1s, find out:
1. all the subsequences where number of 0s = number of 1s
2. max length subsequence where number of 0s = number of 1s
Update:
We need to find subarrays, not subsequences. Sorry for the confusion.
find the substring count from a string without string functions in java?
Given String str = "abcdefghcde";
String find = "cde";
Count occurrences of cde in String str
Given a function
float convex(float x)
WAP to find the minimum value of convex() between x1 and x2. convex is first monotonically decreasing and then monotonically increasing between x1 and x2.
float minima(float x1, float x2)
white your own printf() function in c ?
Using two threads you should print "Hello World Hello World Hello World Hello World Hello World Hello World ".
In two threads one should print "Hello: and another thread "World".
Find whether there is a loop in a given liked list or no?
Solved it using two pointer. He wanted me to prov using mathematics, which I don't know :(.
According to the story, four prisoners are arrested for a crime, but the jail is full and the jailer has nowhere to put them. He eventually comes up with the solution of giving them a puzzle so if they succeed they can go free but if they fail they are executed.
The jailer puts three of the men sitting in a line. The fourth man is put behind a screen (or in a separate room). He gives all four men party hats (as in diagram). The jailer explains that there are two red and two blue hats; that each prisoner is wearing one of the hats; and that each of the prisoners is only to see the hats in front of them but not on themselves or behind. The fourth man behind the screen can't see or be seen by any other prisoner. No communication between the prisoners is allowed.
If any prisoner can figure out and say to the jailer what colour hat he has on his head all four prisoners go free. If any prisoner suggests an incorrect answer, all four prisoners are executed. The puzzle is to find how the prisoners can escape, regardless of how the jailer distributes the hats?
Puzzle : There will be two sticks, if you burn each sticks from one side both will burn for an hour. You don't have any watch or stop watch, How you will measure 1 n half our and 45 min?
Find wether there is a loop in a given liked list or no?
I solved it using two pointers. But they were not satisfied as I knew this solution before. They wanted me to solve using Single pointer.
Print 'n' elements of fibonacci series.
public int fibonacci(int n) {
if ((n == 1) || (n==2)) {
System.out.print("\t" + 1);
return 1;
}
int temp = fibonacci (n-1) + fibonacci (n-2);
System.out.println("\t" + temp);
return temp;Write a code to find subset of numbers in array whose summation= given number? If this does not exist, print false
I know the solution consisting of non-negative numbers.
Is there any smart solution when the array contains NEGATIVE numbers?? Thanks.
In a pocket calculator, a person is randomly typing a 8 digit number. What is the probability that the number looks the same even if the calculator is turned upside down.
Design a maze. Give the algorithm and code to find the correct path and get out of the maze.
Give the algorithm and code to get the depth of the deepest odd level leaf node in a binary tree.
Rotate matrix in 90 degree clockwise.
How can I find if a String exists in a double dimension Array. For eg. Does CAT exist in
'c','b','k'
'd','a','l'
'g','t','i'
It does exist. What will be an optimal way to do it ?
Assume you don't have to move upwards in the Array.
So in the below Array cat does not exist.
'c','b','t'
'd','a','l'
'g','J','i'
given a string in form of an array find an expanded string
e.g. A2B3C4 => AABBBCCCC
also, size of given array is exactly same as expanded string. so return the same array with expanded string.
Find the k'th largest element in a binary search tree. Write code for
struct Node {
int val;
struct Node *left;
struct Node *right;
} Node;
Node * kth_largest(Node *root, unsigned int k);How to Reduce wait time in Elevator Design System?
I am just curious to know if a greedy approach will work fine here?
Gave a string of characters and asked them to store in a binary search tree in such a way that it can be extracted in exactly the same order
Assume I have a log file with list of people with their arrival and departure time at an event that happened in the past.
My task is to find out the maximum number of people present at any time during the entire event? I am not given query time.
ai = Arrival time of person i
di = Departure time of person i
I have a list of pairs like (a1,d1), (a2,d2), (a3,d3).... (an,dn)... It's not in a database.
I apologize as I cannot edit my previous question. I think it had a incomplete description.
Please let me know if you guys still need clarification. Thanks
Displaying employees in the order of their first name and Id (Use Comparator Interface and TreeSet) in java
Given a string, find whether it has any permutation of another string. For example, given "abcdefg" and "ba", it shuold return true, because "abcdefg" has substring "ab", which is a permutation of "ba".
There is an island which is represented by square matrix NxN.
A person on the island is standing at any given co-ordinates (x,y). He can move in any direction one step right, left, up, down on the island. If he steps outside the island, he dies.
Let island is represented as (0,0) to (N-1,N-1) (i.e NxN matrix) & person is standing at given co-ordinates (x,y). He is allowed to move n steps on the island (along the matrix). What is the probability that he is alive after he walks n steps on the island?
Write a psuedocode & then full code for function
" float probabilityofalive(int x,int y, int n) ".
what is use of command line argument in software development.
give any real example where we must use command line argrment (for ex- any system software,application software etc)
Find the nth last element on a singly linked list
How will you design Game of life - http://en.wikipedia.org/wiki/Conway's_Game_of_Life
I was asked to design a meeting scheduler, just like in the Microsoft outlook calendar or the gmail calendar. I proposed that I will create an array of 48 for each day. Every 30 min representing the array entry.
I have to make sure that the next appointment does not collide with a previous meeting.
My solution works fine but it wastes too much memory.
Can anyone please tell me how do I find a better solution to detect collision for meetings.
I don't know all the meetings at the beginning. They will be added randomly later.
Thanks,
Implement print function given an integer without using the built-in print function
Given the English alphabet, 'a' through 'z' (lowercase), and an imaginary onscreen keyboard with the letters laid out in 6 rows and 5 columns:
a b c d e
f g h i j
k l m n o
p q r s t
u v w x y
zUsing a remote control - (up - 'u', down 'd', left 'l', right 'r' and enter '!'), write a function that given a word will produce the sequence of key presses required to type out the word on the onscreen keyboard. The function should return the sequence string.
NOTE: This was an actual question. I didn't pull this from TopCoder.
given sorted int[] A, int[] B. How would you find the maiden that would have been if both were combined to one big sorted array? Use divide and conqure recurssion.
please write method "GetMutualMaiden" and explaint it's time and space complexity
Design a data structure with the following API:
*get
*add
*getRandom
*delete
All in constant time
Sort the input character array based on the dictionary given.
For eg:, If input word is “SHEEP“, sorting will make it as “EEHPS“.
But in the dictionary, E may not be at first. As per the dictionary, if P is first, S followed and E later and finally H.
Then sorted array is “PSEEH“.
how many degrees does 3:15 AM forms in watch.
Implement hash map right from scrach ???
Two files F1 and F2 are there . COmpare these two files for equailty in content. These two file contains the same data only that in between lines there are some extra spaces etc.
lets say in one file, entry is : This is me
In other file it could be : This is #@@ me
So we need to compare the two lines and ignore special character and spaces and compare the contents
What is strategy pattern.
Implement a logic to generate 10 unique numbers
Implement Math.Random functionality without using java utilities. Imagine the range could be till trillion.
He told me that there is a image of size 400x400 using some 16 colors utilitizing 1 byte each. How can we compress the image.
Find the longest common subsequence of two string
Given a function KNOWS(A,B), which returns 1 if A knows B (and not necessarily the other way around) and 0 if A does not know B.
A Celebrity is one who does not know anyone,
and one who is known by everybody.
For a list of N people, find all celebrities in linear time.
Describe the actions performed by two functions:
Publish(user, msg) - publishes a new post on behalf of 'user'
GetNewsFeed(user) - gathers 30 posts from 'user's friends to show on his/her news feed.
I was asked to map out the relations required for holding large amounts of data.
As a followup, I had to calculate the number of machines facebook would have to initially buy to start off using this news feed.
Convert a string of Roman numerals to an integer in O(n) time
We Have 5 balls And We have to find it out in 2 ways that which 1 is havier or lesser..
Given some random letters , For example "a,e,o,g,z,k,l,j,w,n" and a dictionary. Try to find a word in the dictionary that has most letters given
Write a script to compare two files.
One is primary file and other is secondary.
I need to check if secondary file contains each line of primary (may be in different order) and should not contain any extra data.
exmaple:
cat primary
abc
lmn
xyz
cat secondary:
cat secondary
xyz
abc
lmn
then in this case compare function should give true.
Note: file contains may be any thing like html or xml code or other.
An overseas customer is reporting a crash of a released driver which has undergone formal in-house testing. This has impacted their delivery schedule and is looking to cost them millions of dollars in lost revenue. What steps would you take to alleviate this situation and close it off?
Write a function to sum up two polynomials. Design the data structure for polynomial.
This Question was asked in written round on one of the online coding round, The Question was to code this. Question is as follows.
You want to create a staff to use in your martial arts training, and it has to meet some specific requirements.
You want it to be composed of two smaller staves of equal length so that you can either use it as a single staff or as two smaller ones.
You want the full sized staff's center of gravity to be exactly in the middle of the staff.
You have a very, very long branch from which you can cut the pieces for your staff. The mass of the branch varies significantly throughout it, so you use just any two pieces of the same length. Given a description of the mass throughout the branch, determine the longest staff you can make, then return three integers on a single line, the first two indicating the first index of each half-staff, and the third indicating the length of each half-staff.
The input will be given on a single line as a string of digits [1-9], each digit representing the mass of a section of the branch. All sections are the same size and the maximum length of the string is 500. Here is an example:
41111921111119
11119 11119
If the indicated sections are cut from the branch they will satisfy your requirements. They are both the same length, and they can be put together as either 9111111119 or 1111991111, both of which have a center of gravity exactly in the center of the staff.
Center of gravity can be determined by taking a weighted average of the mass of each section of the staff. Given the following distances and masses: Distance: 12345678 Mass: 22241211
Sum of the mass of each section: 2 + 2 + 2 + 4 + 1 + 2 + 1 + 1 = 15 Weighted sum of the masses: 2*1 + 2*2 + 2*3 + 4*4 + 1*5 + 2*6 + 1*7 + 1*8 = 60 Weighted sum / regular sum = 60 / 15 = 4
This means that the center of mass is in section 4 of the staff. If we wanted to use this staff the center of gravity would need to be (8+1)/2 = 4.5.
Here is an example problem:
131251141231 ---- ----
If we take the sections indicated we get 1312 and 1231. By reversing the first one and putting them together we get 21311231
Sum of the mass of each section: 2 + 1 + 3 + 1 + 1 + 2 + 3 + 1 = 14 Weight sum of the masses: 2*1 + 1*2 + 3*3 + 1*4 + 1*5 + 2*6 + 3*7 + 1*8 = 63 Weighted sum / regular sum = 63 / 14 = 4.5
This puts the center of mass exactly in the center of the staff, for a perfectly balanced staff. There isn't a longer staff that can be made from this, so the answer to this problem is
0 8 4
Because the half-staves begin at indices 0 and 8 (in that order) and each is of length 4
Design an algorithm for a restaurant with a host conditions are when ever a person empties his plate the host will be notified. and when ever number of persons waiting exceeds maximum notify the host.
Discuss the design of the following game:
The board consists of the cells of 3 kinds:
ant,
water,
food
if the ant moves to the cell that has ant then both ants are destroyed
if the ant moves to the cell that has water, ant disappears
if the ant moves to the cell that has food, food cell become ant cell.
there are two players, game server.
Write a method that multiplies two integers without using multiply operator
What are the common problems in multithreading programming? Lock, Dead Lock
Discuss IEnumarable/IEnumerator pattern. WAP that implements the pattern for the collection with elements that are collections as well, i.e.:
((1,3,4), (4,5,6), (7,8,9))
input:
sum - the integer amount
n - the number of coins
d - the array contains the coins denominations
WAP that prints all the possible non-repeated combinations of n coins of denominations from d that sum up to n.
Sample of input:
d={1,5,10,15}
sum = 30
n = 6
The expected output:
1,1,1,1,1,25
5,5,5,5,5,5
discuss restaurant reservation system design
Serialize in a file and deserialize a binary tree.
If u have a website in English with all its code now u have to convert the same website to any other language how will u proceed with it ? Suggest all possible methods.
You come to office install the latest build of internet explorer and find out that instead of the expected page explorer loaded a blank screen .. before discussing with developer what test you will like to conduct so that he can pin point the problem from your observation
What is mip-maps and why are they used
Why we use 4X4 matrix for representing and calculations in transformation of 3D points when that can be done only with 3X3 matrix.
(the concept of homogenization of matrices and how they help including translation operation)
What the different shaders(vetex, geomtery, pixel) describe their roles and the order in which they are executed in graphics pipeline
There is an machine which can process any kind of fruit and produce packaged boxes … write test cases for that
'K' number of char arrays of different length are given, find Cartesian product of them in optimal way & give complexity. I used divide & conquer.
Given n, output the numbers from 0 to 2^n-1 (inclusive) in n-bit binary form, in such an order that adjacent numbers in the list differ by exactly 1 bit.
Given a BST, print the node with value between [min, max], i.e. min = 10, max = 17, print the node with value between 10 and 17
Find the common friend between two people in facebook? Use graphs.
• Including the initial parent process, how many processes are created
#include <stdio.h>
#include <unistd.h>
Int main()
{
Fork(); // Fork a child Process
Fork(); // Fork another child process
Fork(); // and fork another
Return 0;
}
Write a function in java to reverse linked list recursively but the function should have void return type?
how would you implement a secondary sorting. Meaning sorting by Category A, and then sub sorting by category B?
Given an array A of N integers, we draw N discs in a 2D plane such that the I-th disc is centered on (0,I) and has a radius of A[I]. We say that the J-th disc and K-th disc intersect if J ≠ K and J-th and K-th discs have at least one common point.
Write a function:
int number_of_disc_intersections(int A[], int N);
that, given an array A describing N discs as explained above, returns the number of pairs of intersecting discs. For example, given N=6 and:
A[0] = 1 A[1] = 5 A[2] = 2
A[3] = 1 A[4] = 4 A[5] = 0
intersecting discs appear in eleven pairs of elements:
0 and 1,
0 and 2,
0 and 4,
1 and 2,
1 and 3,
1 and 4,
1 and 5,
2 and 3,
2 and 4,
3 and 4,
4 and 5.
so the function should return 11.
The function should return −1 if the number of intersecting pairs exceeds 10,000,000.
Assume that:
N is an integer within the range [0..10,000,000];
each element of array A is an integer within the range [0..2147483647].
Complexity:
expected worst-case time complexity is O(N*log(N));
expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments).
Elements of input arrays can be modified.
Write a method that generates a random sequence of numbers of specific percentages
how to find lowest common ancestor of a binary tree
??
not BST
The diameter of a tree is the number of nodes on the longest path between two leaves in the tree. The diagram below shows a tree with diameter nine, the leaves that form the ends of a longest path are shaded (note that there is more than one path in each tree of length nine, but no path longer than nine nodes).
In particular, note that the diameter of a tree T is the largest of the following quantities:
the diameter of T's left subtree
the diameter of T's right subtree
the longest path between leaves that goes through the root of T
Given the root node of the tree, return the diameter of the tree
write the most efficient (in terms of time complexity) function getNumberOfPrimes which takes in an integer N as its parameter.
to return the number of prime numbers that are less than N
Sample Testcases:
Input #00:
100
Output #00:
25
Input #01:
1000000
Output #01:
78498
longest common subsequnce: given two lists, find the longest sublist (in order) that is the same
You are given an array of size N containing negative and positive real numbers. Zero may or may not be present in the array. The requirement is to rearrange the array using O(N) time and O(1) space so that all negative numbers come before all positive elements. Develop a program to read a real number array of size N from user, and then arrange it as explained above.
Constraints :
(i) The value of N has to be read from user, and the memory for array has to be allocated dynamically. The real numbers will be also read from user. The menu-driven program should also have an option to populate the array with random data, if the user wants to do so.
(ii) A maximum of 3 passes allowed over the entire array. O(N) time expected.
(iii) O(1) extra space permitted – creating copy of array etc not allowed.
(iv) Program must work properly even if zero is NOT present in array.
Implement LookAndSay function. For example, first, let user input a number, say 1. Then, the function will generate the next 10 numbers which satisfy this condition:
1, 11,21,1211,111221,312211...
explanation: first number 1, second number is one 1, so 11. Third number is two 1(previous number), so 21. next number one 2 one 1, so 1211 and so on...
There is rotated sorted array.Write the program to find any element in that array
Original Array A={1,2,3,5,6,7,8}
Rotated Array B={5,6,7,8,1,2,3}
Write the program to find any element in array B
Implement DFS for binary tree
There are 2 sorted sets.Find the common elements of those sets
e.g.
A={1,2,3,4,5,6}
B={5,6,7,8,9}
o/p C={5,6}
Complexity should ne 0(n+m) where n and m is the size of the first and second set respectively
Which data structure should be used to store the output
enumurate all phone numbers by the digit dial on the phone keypad
Given a string and a dictionary. Break the string into meaningful words.
write a function to sum two single linked lists that represents binaries numbers
explain and write algorithm that implements and infinite binary counter, where add() takes O(1) time complexity
What is the difference between a class method and an instance method?
Implement a set that supports insert, remove and getRandomElement() operations.
I have 4 files,they are a.abc,b,abc,c.abc and d.abc.
a.abc file contains
file:b.abc
value:4
file:c.abc
value:6
and c.abc file contains
file:d.abc
value:7
file:e.abc
value:3
so now i want to read a.abc file and get the file name and check that file is exist or not if file is exit read the value and print ...these are all based on file hierarchy.
Provide a datastructure that can perform :
1. insert
2. delete
3. find min
4,. find max
5. delete min
6. delete max
all in O(1) time.
How do you remove repeated values from a INT array, returning the resultant array in the same order as original ?
we have given a char array like “a1b2c3″ we have to convert this array to array like this “abbccc” .This has to be done in place as we have given that array has just enough space to hold the expanded array.
example:
1)input: a1b1c1
output:abc
length of array will be shortened.
2)input: a2b2c2
output:aabbcc
length of array will be equal to given array.
3)input: a3b4
output:aaabbbb
length of array will be greater than given array.
Design a scheduling system which can run 10M jobs. Jobs can be scheduled to run on a time of day, some day of the week, a particular day of the month etc.
A robot is placed on an infinite 2D grid. The robot is initially facing the east direction. It moves in a spiral movement turning to its left after each move. The movements are given as an input array.
For example, assume the Robot is initially at (x,y) and the movement array is [4,3,5,2,1,6,...].
After 1st move, Robot will be at (x+4,y)
After 2nd move, Robot will be at (x+4,y+3)
After 3rd move, Robot will be at (x-1,y+3)
After 4th move, Robot will be at (x-1,y+1)
After 5th move, Robot will be at (x,y+1)
After 6th move, Robot will be at (x,y+7)
and so on.
Find the minimum area of the rectangle which can enclose all these points.
Consider a system of n nodes numbered 1 to n. Each node has its id(1 to n) and a value associated with it say val. Now Every node has a send method send(int to , int val) and receive method int receive(int from).
So if node 1 wants to send value , it does like this . send(1,val).
Using these two methods, write a distributed algorithm. Such that when the algorithm finishes, every node in the system knows the sum of the values of all the nodes in the system.
Write algorithm (code) to created a minimal height binary tree from a sorted array.
Have you heard of the data structure called heaps? What do you know about them? Where would you use heaps and why?
What do you know about hash tables? Talk about collisions and collision handling methods. What are the cons of using chaining?
-- Essentially he wanted to hear about complexity and about the effects of chaining on the complexity.
Given a list of interval , find the maximum overlaping. For ex if input is 0,5 2,9 8,10 6,9 then ans is 2 as 8,10 overlap in 2,9 and 6,9
2.write a program to diaplay the advisered average for the list of numbers my omitting the largest number in the series.
eg :3,6,12,55,289,600,534,900 and 172.
avg=(3+6+12+55+289+172) /6and eliminating 534,900,600
1.Substring Addition
Write a program to add the substring
eg :say you have a list {1 7 6 3 5 8 9 } and user is entering a sum 16.Output should display (2-4) that is {7 6 3} cause 7+6+3=16.
You have a bunch of files and folders, Design a playlist which can have any file from any folder and a player that plays it
Count the number of shapes in a given (1/0) matrix. A cluster of consecutive (not diagonal) 1's defines one shape.
eg
1 1 0 0 1
1 0 0 1 0
1 1 0 1 0
0 0 1 0 0
No of shapes = 4
Write a function which compress string AAACCCBBD to A3C3B2D
Given an expression (in single variable) like 4x+13(x-(4x+x/3)) = 9, evaluate x
The expression is a string and the variable is always x.
Given a list of integer numbers, a list of symbols [+,-,*,/] and a target number N, provide an expression which evaluates to N or return False if that is not possible.
e.g. let the list of numbers be [1,5,5] and the target number is 9, one possible solution could be 5+5-1.
C# Question.
class Test
int x;
int y;Where the memory would be allocated ? Since both are primitive datatypes would it be allocated on stack or heap ?
N people race against each other in a pair of 2 . During prize distribution they are arranged in such a way such that on the left side of that person is a person whom the player lost to and on the right side is a person whom he won .Write an algorithm to arrange the players in that order.
Given a list of quantity of books and corresponding prices.User wants to purchase Q quantity of books. Provide an algorithm which suggest user Q Quantity of books with minimum price
e.g
Quantity of Books 10 20 30 15 25
price of books 100 200 120 130 165
user wants to purchase 500 quantity of books.come up with minimum price
Given n positive real numbers, find whether there exists a triplet among this set such that, the sum of the triplet is in the range (1, 2). Do it in linear time and O (1) space.
Given an array sort all the elements in even positions in ascending order and odd positions in descending order
Given an array elements, Find the maximum number which can be formed by the array elements
Eg input – a[ ] = {9,6,8,1]
Output - 9861
Find the occurences of each word in a sentence/
e.g :
"Hi I am there, am good"
am=2, good=1,Hi=1, I=1,there=1
Print in sorted order as per count.
If count is same, it should be alphabetically sorted.
Write a function that gets a billion integers. How can you find the midian in most efficient way (time)?
same question, but the input is an endless stream of integers, and we want to find the current median.
given a maze (matrix bool[N][M]) where 0 = free way, 1= obsticle - How many ways are there to reach from [0][0] to [N][M]? write a non-recursive solution.
Design a web browser like Chrome with the tab functionality.
Also describe the data structure to be used.
merge two unsorted linked-list into one new sorted linked list, off course in a efficient way
Given a ternary string, you have to count the total number of contiguous substrings (contigious set of characters), that you can form from this given string such that they comprise of either only one or two different characters.
Please note that a unique substring will be decided by its starting and ending indices. So, a substring 'ab' with starting and ending indices being 1 and 2 respectively should be considered different from a substring 'ab' with starting or ending indices (or both) other than 1 and 2 respectively.
For example:
input ternary string - aabc
output - 8
The above string comprises of the following substrings that have either one or two of the characters - a, a, b, c, aa, ab, bc and aab. So the final answer is a total of eight substrings.
input ternary string - abc
output - 5
The above string comprises of the following substrings that have either one or two of the characters - a, b, c, ab and bc. So the final answer is a total of five substrings.
input ternary string - baaccb
output - 16
The above string comprises of the following substrings that have either one or two of the characters - b, a, a, c, c, b, aa, cc, ba, ac, cb, baa, aac, acc, ccb and aacc. So the final answer is a total of sixteen substrings
We have array that contain integer number, I would like to find the numbers that repeated k time in this array. The array is not sorted, and the numbers are not bounded.
Example,
A(20, 6, 99, 3, 6, 2, 1,11,41, 31, 99, 6, 7, 8, 99, 10, 99, ,6)
Find the numbers repeated more than 3 times.
Answer: 6,99
possible answer using bit wise operations (xor) or combination? Efficiency in running time Big(o) is required as well as the space capacity.
Given that a disk page can hold at most 1K bytes, a search key uses 4 bytes, and a pointer uses 4 bytes.
Can we analyze the size of an expendable hashing index to index a table column which is defined using unique constraint. What would be the minimum and maximum size of the expendable hasting index if the bucket address table is fully extended?
A tree-map is implemented using BST, the complexity of search in a tree-map is guaranteed to be O(logn). How is that case of search complexity O(n) [obtained when the BST is like a linked list from the root node, only in single side] in BST avoided in tree-map.
Which data structure is preferred for performing concurrency, serialization out of BST and Hash-Table.?
Compare the space complexity of BST and Hash-Table.
Given a BST and a node, write a function to find the next biggest element in the BST in preferred language.
How can we implement a geo location plugin on any browser
Design a realtime service that tells users which of their friends are currently online.
Your service must implement two functions:
// Return a list of friends of `user_id` that are online
List<user_id> getOnlineFriends(user_id)
// Tell the service that `user_id` is online
setOnline(user_id)You may assume that you have access to the function `getFriendIds(user_id)` which returns you a list of all friend ids for a given user id
Given a hashmap M which is a mapping of characters to arrays of substitute characters, and an input string S, return an array of all possible mutations of S (where any character in S can be substituted with one of its substitutes in M, if it exists).
What is the time complexity? What is the space complexity? Can you optimize either?
Example input:
M = { f: [F, 4], b: [B, 8] }
S = fab
Expected output:
[fab, Fab, 4ab, faB, FaB, 4aB, fa8, Fa8, 4a8]Given an array of real numbers A of length n, and some integer k such that 0 <= k < n, write a function that returns the kth largest number in A, where k=0 refers to the largest number.
What is the time complexity? What is the space complexity? Can you optimize either?
Example input: A = [0.5, 2.5, 1], n=3, k=1
Expected output: 1Find an ancestor of given two node from a tree in O(n) time. The tree is binary tree.
Let assume you have access full heap memory. Now design & write code malloc and free operation.
Suppose we are detecting fraud cheques and we found the cheques with the following list of patterns are fraud:
111122234455
1234
22334455
11111111
234567
etc.
Now if you have a new cheque and wan to detect fraud in O(1) time what data structure you want to use?
Suppose a customer buys items for $10 in a shop and the cashier swipe her card at a POS charging $10. Assume that the card has $100 balance before swiping. POS sends the $10 transaction to a machine A in the Amazon cloud. A calls a service to update transaction and card balance, and then sends acknowledgement back to the POS. But the ack got lost in the middle and POS sends another $10 transaction request. How would you make sure that the balance is $90, not $80. And how would you distinguish multiple try with two legitimate $10 transaction back to back.
Hint: You can't use more than one transaction entry in Database and you don't have the rollback provision.
Given a BST and a node, write the BST data structure and a method in Java
Node findNode(Node n)
that will find the next node of n in the BST. For example, if the tree looks like:
7
/ \
5 11
/ \ /
4 6 9
/ \
2 15
Then,
findNode(2) = 4,
findNode(4) = 5,
findNode(5) = 6
findNode(6)=7
findNode(7)=9
findNode(9)=11
findNode(11)=15
Note that you are not given the root of the tree.
Hint: you may assume that you have parent pointer.
Write a java program thats takes a string and a character as input and return the string without that character. Do not use repalce function. For eg google, g should return oole
what's encapsulation
Difference between bit-wise operator and logical operator
Design a GPS system
We consider a Permutation of first 'N' natural numbers 'good' if it doesn't have 'x' and 'x+1' appearing consecutively, where (1 <= x <= N).
• For Example, For N=3, all 'good' permutations are:
1. {1,3,2}
2. {2,1,3}
3. {3,2,1}
Pots of gold game: Two players A & B. There are pots of gold arranged in a line, each containing some gold coins (the players can see how many coins are there in each gold pot - perfect information). They get alternating turns in which the player can pick a pot from one of the ends of the line. The winner is the player which has a higher number of coins at the end. The objective is to "maximize" the number of coins collected by A, assuming B also plays optimally. A starts the game.
The idea is to find an optimal strategy that makes A win knowing that B is playing optimally as well. How would you do that?
At the end I was asked to code this strategy!
Write a program to sum two binary numbers represented as strings.
Input: "110", "01101"
Output: "10011"
Method signature:
public String addBinaryNumbers(String num1, String num2);
Given the root node of a binary tree (not a BST), each node containing an integer value. Print
the values along the path from the root to the node containing the max value.
Given a monotonically sorted 2D array, explain an algorithm to search for a given input element.
A monotonically sorted array is one in which each row and column has elements in ascending order.
E.g. [ 1 2 10; 4 6 11; 5 7 12;] and [1 2 5; 4 6 7; 10 12 13] are both monotonically sorted.
Given a list of words output the largest anagram derivative contained in that set.
The definition of an anagram derivative is:
Consider the word 'cat' as a basis, then the word 'tack' is said to an anagram derivative of 'cat' since it can be re-arranged and appended with an alphabet to form the word 'tack'. This process can be performed repeatedly, so that the word 'tacky' is an anagram derivative of 'tack'.
Now given a list of words output the largest anagram derivative in that list.
Pinterest has access to a large volume of 'pins' say of the order of 10 million. It is now required to display the 'Top 50' pins to the users on the website.
Each pin has an associated 'score id' which is constantly updated as users 'like' the pin.
Explain the run time complexity and memory requirements of the architecture.
How to get common elements from two sorted arrays and you should not use any additional buffers.
ex:- a[] = {1,1,3,4,6,9}
b[] = {1,1,3,4,5,9}
output[] = {1,1,3,4,9}
Implement in OOP the old cell-phones game "snake". Implement the function "MoveUp". Follow up: how would you reduce space complexity?
give examples of hash functions that maps english word to byte
how would you store and find the top 10 queries in google from some day (when you begin to count) till a certain date?
Suppose you are appointed as a Database Administrator in a well reputed organization. Database in that organization is completely indexed. However, it has been noted that query performance of retrieval operations are good, but “write” operations are creating overhead.
Your task is to improve the performance in the given perspective. There might exist different ways to solve this problem. Discuss the solution with strong arguments
Your company has got a project for developing a software system. A similar software system was developed in your previous company. You discover that your company's interpretation of requirements is different from the interpretation taken by your previous company. Cost of project will tremendously increase if ambiguities in requirements are not resolved. You have also an ethical responsibility of confidentiality to your previous company. Discuss what you should do in such a situation? not please give me answer in a few hours that i submit my topic at time
As input, you are given two sets:
1) set R of n1 non-overlapping rectangles, whose sides are parallel to the x- and y-axes (ie: not rotated rectangles). Each rectangle denoted by bottom left & top right corner coordinates.
2) set P of n2 points
- let n = n1 + n2
For each point 'p' in set P, find the rectangle 'r_p' in set R that contains 'p'. If 'p' is not enclosed by any rectangle, then 'r_p' is undefined. Otherwise, 'r_p' is unique because of the non-overlapping set.
Goal: come up with a divide-and-conquer pseudocode to solve the general problem in O(n(logn)^2) time.
Asked about points that are on the edge of the rectangle, and they said it was up to me whether to include those or not, just a matter of "<" vs "<=", etc. comparisons. Because it's just pseudocode they were looking for, they were not too concerned with the actual structure of the return value, just that the D&C algorithm showed the logic.
Struggled with it for awhile and they simplified the problem to a ~special case with the constraint where all rectangles of R intersected a horizontal line 'L', and instead give a O(nlogn) algorithm to solve the same problem. I suspect this would've been a subproblem/subroutine of the more general case, but again got a bit lost.
Given an infinite sequence of integers which are repeated many times. WAP to print "beep" if an integer appears ODDth time else print "no beep".
example: input: a[] = { 1,4,2,4,3,2,4}
output: beep, beep, beep, no beep, beep, no beep, beep
Space complexity - O(1)
You have a number L and N distinct integers between 1 and 100.
You can use each number as many times as you want. Print the minimum subset size of these numbers which add up to L and how many ways are there to choose them (the order does not matter).
0<L,N<=100
examples:
input1:
L=7 N=6
2 1 5 4 3 6
output1:
2 3 (minimum 2 numbers, 3 ways to choose: 1 and 6, 2 and 5, or 2 and 4
input2:
L=7 N=3
4 2 6
output2:
0 0 (can't get 7 from 4,2 or 6)
input3:
L=14 N=3
8 7 1
output3:
2 1 (we choose 7 twice)
input4:
L=100 N=3
2 97 1
output4:
3 1
void populate(char **s);
int main() {
char *s;
populate(&s);
printf("%s", s); // should print "Prasad"
free(s);
return 0;
}
void populate(char **str) {
// 1. The next two lines is one implementation
*str = (char *)malloc(sizeof(char) * 7);
strcpy(*str, "Prasad");
// 2. This line seperately is another implementation
*str = "Prasad";
}What is wrong, if anything, with the two implementations of populate.
How to detect cycles in a graph?
Don't need to write code, just your idea and complexity.
give bi matrix 5 dimensional array
{1 ,2, 3, 4,6},
{5, 4, 3, 5,7},
{6, 5, 9, 8,9},
{9, 8, 7, 6,1},
{1, 8, 3, 6,2}
the output that needs to print is
1
25
346
4359
65981
7878
963
16
2
write an algorithm in java
clue size of the bi dimensional array
and factorial of the size
and verify the indexes of the numbers in the output
for each number
they form a pattern
write in a paper all the indexes
ull understand the pattern
What are uses of Btree, AVL and RBtree(individual applications as i explained that we use them whenever we need balanced BST and he wasnt convinced)
When would you specifically use Btree over AVL tree.
Which one out of balanced BST is most efficient(for which i answered Btree for large values of n) and he asked why dont we always use Btree then?
what is volatile in java
What is IOC container and how did that works, and explaining the pros and cons.
Design a phonebook dictionary which on input any characters gives names and phone number of all the matching names(prefix)
For instance
Rihana 233222232
Ricky 134242444
Peter 224323423
Ron 988232323
If you give R as input it should list
Rihana Ricky and Ron which their contact numbers
If you give ri as input it should list
Rihana, Ricky which their contact numbers
WAP :
public boolean hasUniqueChars(String a);
- String can contain any type of chars
- You cannot use any type of Collections
for this code:
class Interview {
// input is max 3 chars
public static int convertToString(int input) throws IllegalArgumentException;
}write a method which checks whether the proper exception is being thrown.
write as many test cases for this : example : 123, 1, 2,... -123, 0,...
class Interview {
// input is max 3 chars
public static int convertToString(int input) throws IllegalArgumentException;
}Write a function, that given a list of integers and an integer s, prints any 2 numbers in the list that sum to s.
1, 2, 3, 4, 5 sum = 6 could print:
1 + 5 = 6
2 + 4 = 6
4 + 2 = 6
5 + 1 = 6
Given a string, find the longest substring that occurs more than once. Overlapping is allowed.
I have a virtual function in base class BASE and in derived class DERIVED, I have overridden the virtual function. I will create 10 object of DERIVED class.Ex: DERIVED d1,d2...d10. How many v tables are created in this scenario?
swap alternate bits of a given number
eg: n=5 (0101)
output: 10(1010)
n=8(1000)
output:4(0100)
Given a binary tree return the level with maximum number of nodes
1
/ \
2 3
/\ /\
4 5 6 7
/ \
8 9Append the last n nodes of a linked list to the beginning of the list
eg: 1->2->3->4->5->6
if n=2
5->6->1->2->3->4
Print the last n lines of a file in one iteration
Implement Queue using stacks
Given a file which contains list of function with parameters and return types (Assume parameters and return type as primitives) they can be of any order
Example: File functions.txt contains below info
int e=f1(a,b,c,d)
int c=f2(a,b,d)
f3(a,c)
float d = f4()
question follows as below
We need to implement function
execute(functions.txt,a,b,d) where functions.txt is the file which contains just functions info and a,b, d are input parameters of functions defined in the file.
Now read the file and we need to determine the order of execution of function depending on the input parameter list
we can't execute f1 first because we have only parameters a , b and d
f2 can be executed because we have a, b and d parameters, which gives parameter c
now f3 can be executed because we have parameters a and c..
so we need to find the order and execute functions as quickly as possible (can use multi threading)
so efficient order is
f2 and f4 can run parallel and then f1 and f3 can be started only after completion of f2.
What are the data structures we use here to solve this problem
Consider execute function which takes always 1st parameter as filename and the rest of parameters as dynamic (similar to ... in java for dynamic parameter list)
find the distance between 2 values in a binary search tree. Node will have value, left node and right node
implement the function int Distance(Node root, int val1, int val2) without recursion
int Distance(Node root, int val1, int val2) {
if(val1== val2) {
return 0;
}
while((root.val<val1 && root.val <val2) || (root.val >val1 && root.val2 >val2)) {
if(val1 < root.val) {
root = root.left;
} else {
root = root.right;
}
}
return depth(root, val1) + depth(root,val2)
}Note: function depth(root, val) returns the depth of sub tree. Interviewer is ok about the depth of tree functionality but he asked me if Distance(Node root, int val1, int val2) implementation is correct.
Complexity is O(logN)
Write test cases for stringreversewords(string actual)
Five tree in a row and one monkey. monkey can jump left or right. find out best strategy to kill monkey. large amount of ammunition available.
Some suggest solution by two shot at every tree and start from one end.
I doubt it will fail!!
Does any strategy exist ??
Given a multidimensional array with only 0s and 1s, reverse the array! I guess what he meant was flip 0s to 1s and vice versa! The array could be of any dimension ex:4X4X4X4....
(I dint get this q's so asked for another!)
Given a char array color[]={'a','b','c','d','e','f'.......'z'}
and a random array arr[]= {'f','a','b','b','z','a','a','a'}
you need to sort them such that resultant array will be {'a','a','a','a','b','b','f','z'}.
Conditions:
1) You should use swap function.
2) Every element may repeat minimum 5 times and maximum 26 times.
3) 'a' can be swapped only 1 time, 'b' can be swapped max 2 times,'c' can be swapped 3 times ...... z can be swapped max 26 times.
4) You cannot make elements of given array to 0.
5) you should not write helper functions.
Input will be of 100 elements each.
Given a 2D binary array (2D array of 0's and 1's) with 'm' rows and 'n' columns, give an efficient algo to find area of the largest sub array(rectangle) consisting entirely of 1's.
Which is best data structure among following for recursion?
Array
stack
queue
linked list
If have unlimited memory, how can we achieve concurrency between threads without using locks?
Find max depth of a binary tree
Disadvantages of locks? What is Deadlock? What is Starvation?
How would a mutex lock be implemented by the system?
How is mutual exclusion done in C++?
How would you implement Garbage Collection in C++?
WAP to find the fibonnaci numbers between 0-32
You have a cake and you have a knife,you have to cut(straight) cake into 8 parts by using knife 3 times,
for example cutting cake horizontally and vertically from middle you had make cake in 4 parts by using 2 times knife
There are 500 bulbs in the hall of a palace. The switch control(with 500 switches) for these bulbs is located in another room. Unfortunately the switches are not marked with the bulb numbers. A new worker arrives. What is the minimum number of trips he has to make to the hall to know exactly which corresponds to which bulb?
Suppose that we have a sorted singly linked list with integer values. For example:
1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7
We want to change the pointers of this linked list so that it becomes:
7->1->6->2->5->3->4
I did not have enough time left to finish my code and I could not think of a good solution.
Write a method to compute the difference between two ranges. A range is defined by an integer low and an integer high. A - B (A “minus” B) is “everything in A that is not in B”
Given N arrays with sizeof N, and they are all sorted, if it does not allow you to use extra space, how will find their common datas efficiently or with less time complexity?
Imagine you have a sequence of the form 0123456789101112131415... where each digit is in a position, for example the digit in the position 5 is 5, in the position 13 is 1, in the position 19 is 4, etc.
Write a function that given a position returns the digit in that position.
(You could think that this sequence is an array where each cell only holds one digit so given an index return what digit is in that index, however you cannot really create an array since the sequence is infinite, you need a way to based on the index calculate the digit that goes there).
The function has to return a single digit.
Other examples:
index = 100, result = 5
index = 30, result = 2
index = 31, result = 0
index = 1000, result = 3
There are two strings, String 1 and String 2 remove the characters from string 2 which are present in string 1
Example: String 1: Amazon, String 2: And
O/p: mzo
There is a square shape of cake and you are allowed for 3 sharp cut
how will you cut cake into 8 equals parts
We are given an array of 2n integers wherein each pair in this array of integers represents the year of birth and the year of death of a dinosaurs respectively. The range of valid years we want to consider is [-100000 to 2005]. For example, if the input was:
-80000 -79950 20 70 22 60 58 65 1950 2004
it would mean that the first dinosaur had a birth year of –80000 and an year of death of –79950 respectively. Similarly the second dinosaur lived from 20 to 70 and so on and so forth.
We would like to know the largest number of dinosaurs that were ever alive at one time. Write a method to compute this, given the above array of 2n integers.
Write a code to extract individual blocks from a given matrix....
Eg: if we have a 4x4 matrix you need to extract 2x2 independent matrices and store them in 4 different arrays...
Given matrix:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
For the above matrix the output should be as follows..
Array1: 1 2 5 6
Array2: 3 4 7 8
Array3: 9 10 13 14
Array4: 11 12 15 16
Given a sentence and a function isValidDictionaryword(String s), which returns true if the word is present in dictionary. WAP to separate valid dictionary words in the sentence with a space.
I/P : thereisastoneontheroad.
O/P : there is a stone on the road.
Below question was asked in online coding exam for Palantir Technology, Palo Alto, CA. Time given was 100 min. I could not complete it by the time.
-----------------------------
A group of farmers has some elevation data, and we’re going to help them understand how rainfall flows over their farmland.
We’ll represent the land as a two-dimensional array of altitudes and use the following model, based on the idea that water flows downhill:
If a cell’s four neighboring cells all have higher altitudes, we call this cell a sink; water collects in sinks.
Otherwise, water will flow to the neighboring cell with the lowest altitude. If a cell is not a sink, you may assume it has a unique lowest neighbor and that this neighbor will be lower than the cell.
Cells that drain into the same sink – directly or indirectly – are said to be part of the same basin.
Your challenge is to partition the map into basins. In particular, given a map of elevations, your code should partition the map into basins and output the sizes of the basins, in descending order.
Assume the elevation maps are square. Input will begin with a line with one integer, S, the height (and width) of the map. The next S lines will each contain a row of the map, each with S integers – the elevations of the S cells in the row. Some farmers have small land plots such as the examples below, while some have larger plots. However, in no case will a farmer have a plot of land larger than S = 5000.
Your code should output a space-separated list of the basin sizes, in descending order. (Trailing spaces are ignored.)
While correctness and performance are the most important parts of this problem, a human will be reading your solution, so please make an effort to submit clean, readable code. In particular, do not write code as if you were solving a problem for a competition.
A few examples are below.
Input:
3
1 5 2
2 4 7
3 6 9
Output:
7 2
The basins, labeled with A’s and B’s, are:
A A B
A A B
A A A
Input:
1
10
Output:
1
There is only one basin in this case.
Input:
5
1 0 2 5 8
2 3 4 7 9
3 5 7 8 9
1 2 5 4 2
3 3 5 2 1
Output:
11 7 7
The basins, labeled with A’s, B’s, and C’s, are:
A A A A A
A A A A A
B B A C C
B B B C C
B B C C C
Input:
4
0 2 1 3
2 1 0 4
3 3 3 3
5 5 2 1
Output:
7 5 4
The basins, labeled with A’s, B’s, and C’s, are:
A A B B
A B B B
A B B C
A C C C
You are given two array lists. One Array List contains information of latitudes and longitudes of all the amazon stores and another array list contains all the possible values of latitudes and longitudes. Find an optimal way to find out all the latitudes and longitudes which are nearest to one pair of amazon store.
ArrayList<latitude, longitude> AmazonStore;
ArrayList<latitude, longitude> World;
Write some functions in c/c++ and then re-write the same function that can improve performance(cpu/memory etc) and explain why?
How do you handle a misspelled word in a web search engine? (I explained about Longest common subsequence and edit distance as well as Trie).
Following is an interview question asked by 'Amazon' to me. I still haven't come up with a optimized solution.
Problem Statement:
Given an unsorted array of integers n. Return 'true' if the addition of any integers from that array matches with the target value else return false.
Note:
1)'n' could be 1000 or 10,000.
2) Target value could be 'negative'
Test Condition:
i/p:- Array A[]= {-5,6,7,1,0,12,5,-6,100}
Target = 13
o/p:- TRUE
As, 6+7=13.
If we try to do it linearly or normally it will take O(2^n) time complexity.
So I am looking for any method or algorithm which will optimized this problem more.
A spreadsheet consists of a two-dimensional array of cells, labeled A1, A2, etc. Rows are
identified using letters, columns by numbers. Each cell contains either an integer (its value) or
an expression. Expressions contain integers, cell references, and the operators '+', '-', '*', '/'
with the usual rules of evaluation – note that the input is RPN and should be evaluated in stack
order.
Write a program (in C, C++ or Java) to read a spreadsheet from ‘stdin’, evaluate the values of
all the cells, and write the output to ‘stdout’.
The spreadsheet input is defined as follows:
• Line 1: two integers, defining the width and height of the spreadsheet (n, m)
• n*m lines each containing an expression which is the value of the corresponding cell
(cells enumerated in the order A1, A2, A<n>, B1, ...)
Your program must output its data in the same format, but each cell should be reduced to a
single floating-point value. For example, we would expect the following expect to produce the
indicated output:
Input Expected Output
3 2
A2
4 5 *
A1
A1 B2 / 2 +
3
39 B1 B2 * /
3 2
20.00000
20.00000
20.00000
8.66667
3.00000
1.50000
The above example input visually looks like:
| 1 | 2 | 3 |
--+-------------+-------+--------------+
A | A2 | 4 5 * | A1 |
--+-------------+-------+--------------+
B | A1 B2 / 2 + | 3 | 39 B1 B2 * / |
------------------------+--------------+
Write a function that gets a number n and prints out a random list
of numbers 1..n to the screen. For example:
randlist(5) : 1 5 3 2 4
randlist(6) : 4 6 1 5 3 2
This should be truly random (uniformly spread) and with a O(n) complexity.
Every number should appear only once. Random(n) is given as a tool you can use to generate a
single random number between 1-n
Write the following function
void drawLine(byte[] img, int len, int wid, int r, int x1, int x2)
such that you draw a line from x1 to x2 at row r.
len is the length and wid is the width of the image/canvas.
Setting a pixel on to draw the line is to set the corresponding bit on the img array
Each byte corresponds to 8 pixels, that is each pixel is a bit in the array
Find the maximum no of the ordered set (a,b) where a*b = k^2.
Constraints:
1. a,b and k are all Integers.
2. k ranges from 1 - 10^10.
3. Output required in less than 2 seconds.
1. Write a program for returning all pairs that map to a value...Discuss different implementations.
1. Write a program to return a max BST within a given B-tree
1. Write an program to check for anagrams. Discuss different implementation. like using extra space and without using extra space.
1. What is a Hash Map..? Describe its two implementation.
2. Difference between Arraylist and linkedlist in JAVA.
3. Discuss issues in implementing HashMaps...collisions mainly...and how to fix them.
4. What is run-time polymorphism in JAVA..explain with example.
Write an effeicient code to get one's complement of a given integer number withou using any extra space(dnt convert in to its binary to string)
Given a binary tree, find a binary search tree which is a subtree of the given binary tree and has the largest size?
Note : Here size means the no. of nodes and the binary tree can have more than one B.S.T. as its subtree.
Given two linked lists combine them in a way such that the resultant must contain the elements alternatively from one list and the other list?
For ex.
LL1 : 1->2->3->4
LL2 : 5->6->7
Result : 1->5->2->6->3->7->4
Also provide test cases for the algorithm ?
Give an algorithm which removes the occurrence of A and I from string ? The algorithm must be in-place.
N players with weights are given as input. divide them into 2 teams with equal weights. while dividing , ensure that difference in number of players in each team is minimum. output the difference in number of players in 2 teams.
input weights - 3 2 1
output - 1
a string contains oly 3 characters in a string -'a','b','c' . if in the string, 2 different chars occur together they are replaced with the third char. operation is repeated till no reduction is possible. the string must be evaluated from left to right always.
input - abbc
output- 1
You are given an unsorted integer array of size N. This array contains integer from range 0 - N (not necessarily distinct and same integer can appear multiple time in an array).
You need to find pair of all the elements in array which sum up to N.
First i gave a solution using an extra array of size N to keep count of each integer in original array and was able to give solution in O(n) Time complexity and O(n) space complexity.
Then interviewer asked me to decrease space complexity, for which i gave solution as sorting the given array (in nlogn time) and then find the pairs in O(n) time, and hence total time complexity was O(nlogn) and space complexity as O(1).
But interviewer kept pressing for a better time complexity (than O(nlogn)) with O(1) space complexity.
How is it possible, i could not think of any way.
Implement the Huffman compression algorithm as shown in the example below:
1) Given a string AAAAAABBCCDDEEFFFFF, group them according to the number of occurrences: A => 6, B => 2, C => 2, D => 2, E => 1, F => 5
2) Concatenate them according to their number of occurrences (adding the number of occurrences while doing it)
3) Put the concatenate strings in a tree-like structure:
ADEBCF(19)
/ \
/ \
/ \
/ \
/ \
/ \
/ \
ADE(10) BCF(9)
/ \ / \
/ \ / \
/ \ / \
A(6) DE(4) BC(4) F(5)
/ \ / \
/ \ / \
/ \ / \
D(2) E(2) B(2) C(2)The company is currently traded at EV/EBIDA = 5.0x, EBITDA = $120 mln. The company is planing SPO of $120 mln, where $80 mln - secondary shares (current shareholder X sales his stake - 20% of equity capital prior to the SPO) and $50 mln - primary shares (new shares issue).
Please calculate: EV an equity value prior and after SPO
You have given an array of Integers of size n, and a sliding window by 1 integer ,of size k <= n. you have to print minimum number in each window of size k.
E.g: given array [3,9,0,3,18,6], i.e.n = 6 and window size k = 3
available windows for above array is [3,9,0] ,[9,0,3],[0,3,18], [3,18,6]
output should be : 0, 0, 0,3
You have gine n points with x and y cordinates (2 D), and you have to print how many of them are capable of forming a square and for each square print the points that are forming the square.
You are given a list of a million (x, y) map co-ordinates of restaurants on a Tape disk. You are also given what your co-ordinate is (a, b) .
You are required to give out the nearest restaurant in terms of distance. You are free to assume that the distance is measured on a straight line basis (bee-line).
You cannot hold all the million data simultaneously, and design an efficient data structure to complete this task.
How volatile is implemented by compiler? is it just by disabling optimization of the code which uses the variables qualified with volatile or something more than that?
How do you parse a phone number from a huge database of a 'n' billion webpages in 30 minutes ?
Designed a similar API like malloc, which has a similar functionality. How do you test the API ?
Print all the permutaion of a given string.
1) explain time\space complexity?
2) how can you improve time\space complexity?
find whether two strings are anagrams in theta(N) time.
Here N is the length of either of the strings given as input.
Create an OO design for a Rubix's cube and implement the method rotate.
Is any specific use of empty class??
implement your own sizeof() operator..
How the JVM is implemented to handles try catch finally .
Elaborate by taking any JVM.
What are the run time exceptions in java related to class and object creation??
class A{
...
dosomething();
..
}
class B extends A{
...
dosomething();
donothing();
...
}
class C expends A{
}
A a =new B();
a.donothing(); //which type of error
B b=new A();
A a1=new C();
B b=(b)a1;Pls give input for anyother cases you may think better.
Write a program to fill a crossword puzzle, given an empty 2D array, the starting positions of the to-be-filled words in the array and the length of each word and a dictionary of words.
Also, come up a appropriate DS for the words in the dictionary that can be specifically advantageous to this problem.
Given a 2D array of chars and a raw list of valid words.
1) Find all the valid words from the array. From each element in the array, you can traverse up, down, right or left.
Eg,
g o d b o d y
t a m o p r n
u i r u s m pvalid words from the above 2D array -> god, goat, godbody, amour,....
2) Also, find a suitable DS to store the raw words list.
I used a recursive approach to solve the problem in exponential time. Can't think of any better approach.
Design search functionality for an ebook reader application in hand held device ? What will be the components involved? Consideration of facts before design . Users must be able to search a word in the ebook using this feature.
If you are given an array of 0 and 1 in sorted order of unknown size, how will you find out the first occurrence of 1 in the array.
How to maintain a Singleton in clustered environment
Program to calculate a power n
Program to calculate a pow n...
I gave a answer with O(logN)
public static long exp(int a , int n)
{
boolean is_N_Odd = false;
if ( n % 2 > 0 )
{
n++;
is_N_Odd =true;
}
if ( n == 2 )
return a * a;
else if (n == 1 )
return a;
else
{
long calc = exp (a , n/2) ;
if ( is_N_Odd )
return calc * calc /a;
else
return calc * calc ;
}
}How to maintain locks/monitors in clustered environment ?
How to manage a singleton in clustered environment ?
How to manage multiple Database drivers ?
Basically how to use DriverManager to register and retrievee multiple drivers
A Query to delete duplicate rows ....
Let say i have a table
Employee - Emp_id,Emp_name,Emp_email
and there is no primary/unique key
Emp_id,Emp_name,Emp_email
1 abc a@b.com
1 abc a@b.com
2 abc a@b.com
Retain only unique rows for Emp_id,Emp_name,Emp_email like ,
Emp_id,Emp_name,Emp_email
1 abc a@b.com
2 abc a@b.com
How Denormalization improves performance ?
Time complexity of Hash Map storage and retrieval in Java.
What are immutable objects? What are their Advantages? Design a immutable object with Date object as a member attribute. NOTE : Since Date is mutable, he wanted to check whether I could resolve that. I dint though :(
Which Design patterns have you worked on? What is Singleton? Design a Singleton Class. Make it thread safe.
Based on typical mobile phone keypad
1 2 3
abc def ghi
and so on
let say if i type 123 what are the possible words.
Read a file and create a a datastructure which holds all the anagrams of words conatined in the file..
For e.g lets say file content is "abc bca"
we need a DS to say "abc" and "cba" are anagrams.
I told i will use a FileReader to read characters than bytes
and assing a prime number for each alphabet
say
a - 2
b - 3
c - 5
and calculate the compound ofr multiplication
say abc = 2 * 3 * 5 = 30
bca = 3 * 5 * 2 = 30
i will use the compound a key in hashmap.
like 30 = abc-> bca -> cba
Let me know for any other better solution
Fnd the sum of elements of an array of ints without using for loop ,,,for eg...input is 1 4....it means we have to find the sum a[1]+a[2]+a[3]+a[4]...range can be upto 100000
How OS decide how much memory is needed as virtual memory ? Max % of memory which can be available as virtual memory?
How can we implement search a keyword in using selected websites?
I want to know How to implement following tech stuff. And I want to know any existing api / plugin/ ready to use logic is available for this.
I want to design custom search engine which can search to specific websites.
and we can add/edit/delete websites from search results.
Like In a google if we want to search a keyword from 5 diff sites
"best ecommerce" site:www.A.com OR site:www.B.com OR site:www.C.com OR site:www.D.com OR site:www.E.com
So we get result from this sites only.
So Please letme know is there any plugin available in wordpress, .net, etc
: Implement a circular queue of integers of user-specified size using a simple array. Provide routines to initialize(), enqueue() and dequeue() the queue. Make it thread safe. Please implement this with your own code and do not use any class libraries or library calls.
Given a BST and a value x. Find two nodes in the tree whose sum is equal x. Additional space: O(height of the tree). It is not allowed to modify the tree
How will you Design Twitter Trends. Suggest Algorithm for this
Given a list of n gas station of form P(D,X) where D is the distance from this station to next station and X is the amount of petrol available at this station, identify the starting station from where you can complete journey to each station in order from 1.....N. You can only go in one direction i.e from P(i) to P(i+1)
EDIT: I forgot to mention that travelling distance K consumes K units of gas.
EDIT2: I proposed an O(n^2) solution, then interviewer asked me if I can do better.
Spiral traversal of a two dimensional array of m rows and n columns. For example, a 2d array with elements a[][3] = { 1,2,3, 4,5,6 ,7,8,9} , the output must be 1 2 3 6 9 8 7 4 5.
Given a linked-list and 2 integers k & m. Reverse the linked-list till k elements and then traverse till m elements and repeat.
A solution takes 8 hours to do n independent jobs. What will you do to improvise?
Follow up: Improvise on a single processor
Follow up: If N task work uses shared memory
How to design Hash map using array.
Design a database for storing record of students.
Develop and algorithm to reverse a string keeping words intact. Example: This is a question
result should be: question a is This
Develop an Algorithm to implement queue using stack
Three coke machines. Each one has two values min & max, which means if you get coke from this machine it will load you a random volume in the range [min, max]. Given a cup size n and minimum soda volume m, show if it's possible to make it from these machines.
With a set 'S' of 'n' numbers {a(1), ... , a(n) } , determine if S contains a 4-term arithmetic sequence with:
a(k) = a(i) + 2(a(j) - a(i)) and a(l) = a(i) + 3(a(j) - a(i)) ; a(i) != a(j)
where the four terms are {a(i), a(j), a(k), a(l) }.
Output boolean.
Example:
Input: 31, 8, 2, 9, 5, 6, 12, 11, 20
Output: True - because {2,5,8,11}
Recruiter tried to lead me in the direction of adapting the 3SUM alg'm to get a runtime of O(n^2(logn)).
For a given binary tree, print level order nodes in reverse i.e Bottom to Top in different lines.
Flip a monochrome bitmap around its centre-line, where input is: char *bytes, int width, int height .
Example:
Input
0101 0110
1111 0011
Output
0110 1010
1100 1111
Given two sorted arrays A{1,2,4,7,9} and B{2,8} have to combine two arrays which leads to third array which is sorted.
Given array A={1,4,3,6,9} and B={2,8,4,3}. Find best approach to print values from array A which are not present in B. Output should be --{1,6,9}
Given a two dimensional matrix of booleans, there is a function that returns the number of "true regions".
A region is a group of True values aligned vertically or horizontally.
T T <= 1 region
T F
T F <= 2 regions
F TQuestion 1: How would you test a function that solve this problem, but is written by another developer. How many tests cases do you see?
Question 2: Now write the code to solve this problem. What are the time and space complexities?
Given a string, find the start position of the largest block of repeated charactes.
After the solution, I was asked to write down as many test cases I could to test the function as if it was created by someone else.
Given two arrays of ints that are sets, create a function to merge them to create a new set.
A set must pass on these three conditions:
- All values are positive
- Sorted
- Non-duplicates
Tell me if a array of integers is a set.
A set must pass on these three conditions:
- All values are positive
- Sorted
- Non-duplicates
After the first solution, I was asked about time and space complexity and to create 5 test cases for my function.
write a pseudo code to calculate
func(n) = 2*(func(n-1)+func(n-2)) in log(n) complexity.
Given:.func(1) = 1;func(2) = 3.
What is initial matrix because of factor 2.
Find the longest tree walk in a tree. The question is to print the longest path in a tree. the path need not got through the root. The path should be between two leaves.
You have a link list with the following structure:
struct Node{ Node*next; Node*other; }
next pointer points to next node, but "other" pointer points to any node in the list, it can be itself or null.
you receive the header of a list with this structure.
you have to copy it(allocate new memory) , you cannot modify the structure, you can not modify the list you are given.
Tell me about another project you have done, how did you do it? what are de difficult parts of it?, tell me everything
Test a program that receives 3 inputs (the size of each edge of a triangle). the program should return :
1 for equilateral
2 for isoceles
3 for scaleno
0 for not triangle
you have to give several test cases for the program
You receive a string with the following characters: '{' '(' '[' ']' ')' '}'
the string can be any size, any number of each character.
You have to decide if the string is balanced, for examplo
{()[]} - correct
(({)}) - incorrect
{()) - incorrect
Microsoft recruiting final round:
Interview 1-Question 4:
Tell me about any software you like, how would you improve it? what bugs have you found?, how would you solve those bugs?
Microsoft recruiting final round:
Interview 1-Question 3:
Tell me about your projects what problems have you had and how did you solve them
Microsoft recruiting final round:
Interview 1-Question 2:
How would you test an elevator
Microsoft recruiting final round:
Interview 1-Question 1:
Insert node in a sorted singly linked list
What is the Minimum Amount not possible using an infinite supply of coins (Unbounded knapsack)
You are given coins of
Denominations {v1, v2 , v3, v4 ....vn } of weight {w1, w2, w3 .....wn}
Now that you have a bag of capacity W .
Find the smallest Value V that is not possible to have in the bag.
(Note , you are not trying to maximize the value V)
Given a very very very large integer(with 1 million digits, say), how would you convert this integer to an ASCII string
Write a long running program in C. This program should not hog the CPU, use no sleep()/block()/select()/wait(), should not block resources...and should terminate after a very very very long time
Find the 2nd largest element in a binary search tree
a. How does OS detects a device on boot up, how does it gets to know whether it is working or faulty?
b. How does the device driver initialize this device (initialization, registration etc)?
What is pass by value and pass by reference?
a. Can a structure be passed by value?
b. Can an array be passed by value?
How will you implement a T9 dictionary? (requiring only 1 look up, no partial searches meaning one keys in a name and then presses go to find it)
How will you tell whether a given number is a palindrome?
Edit: The question was for a string actually.
How will you reverse a given number? (not using "/", "&" operators)
For eg 756 - > 657
You have a sequence of data which tells about daily prices of a stock (of a company in some market). Given the sequence for N such days tell when should one buy and sell to maximize the profit. (for simplicity Assume you can buy only 1 stock). Prices of stock is same for a single day and you cannot buy and sell on the same day.
Edit: You have to buy once only and sell once only. (I also misunderstood Q during interview that we have to tell sequence of buying and selling but it was not the question)
There are 50 Red and 50 white balls. and two back.
Put all these balls in two bag such that if we pick any of the bag, probability of getting red is maximum .....
Defining a tree as such that the parent node always contains the sum of children nodes.
Coul be something like this):
private static int p_get_nodes_value_sum(TreeNodeCollection v_tree_original)
{
//TreeNodeCollection a_child = v_tree_original.ChildNodes;
//TODO:sum the child nodes
int a_suma = 0;
foreach (TreeNode a_child in v_tree_original)
{
if (a_child.ChildNodes.Count > 0)
a_suma += p_get_nodes_value_sum(a_child.ChildNodes);
else
a_suma += Convert.ToInt16(a_child.Value);
}
return a_suma;
}
public class TreeParentSum: TreeNode{
public TreeParentSum(TreeNode v_tree)
{
int a_sum = p_get_nodes_value_sum(v_tree.ChildNodes);
TreeNode a_node = new TreeNode("PARENTNODE", a_sum.ToString());
a_node.ChildNodes.Add(v_tree);
}
}
Write a program to find the unique char in the ascii string.
Given an integer, return all sequences of numbers that sum to it. (Example: 3 -> (1, 2), (2, 1), (1, 1, 1)). Interview was for a php position.
How you maintain the list of top selling product (like on Amazon). Also how you update list based on user like and unlike for a particular product.
Write a method to validate that given Binary tree is a BST.
There are elements being inserted in a HashSet. Print all the values in the order in which they are inserted.
Change the structure of a Tree node to hold a pointer for the next in-order element (sucessor).
Given a Binary Search Tree.. transform it on a LinkedList by setting the next pointer described above.
Maybe this is a duplicate question.
Implement a shared int pointer in C++ (SharedIntPtr).. the use would be like this:
SharedIntPtr a(new int); // reference count 1;
SharedIntPtr b(a); // reference count 2;
*a = 2;
cout << *b; // "2";
a.reset(); // reference count -> 1
*a // <- NULL
b.reset(); // reference count ->0 , object is deleted.There is also this reference count which tells how many references do you have.
And the question was: Implement SharedIntPtr, constructors and reset().
Print all combination of given length k possible with characters available in a given string "S" with repetition in new lines.
Example
S="abc"
k=2
output:
aa
ab
ac
ba
bb
bc
ca
cb
cc
Whats the difference between Semaphore and Lock in Java?
We are given a matrix of MxN elements with each element either being 0 or 1.Find the shortest path between a given source cell to a destination cell.
An element value of 0 means we cannot create a path out of that cell
You are given two Strings lets say "S" which consist Upper Case albhabets and '?' character only and p. You are required to replace '?' with some alphabet so that resulting string have maximum number of "p" in it. You can replace '?' with any alphabet.
2. Replace '?' such that it should be lexicographically sorted.
Example
S="ABAAMA????MAZON????????"
p="AMAZON"
The final string S = "ABAAMAZONAMAZONAAAMAZON"
S="?????"
p="ABCD"
Final Result="AABCD"
Soln:- Proceed from the end of the String.
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
int main()
{
char S[]="ABAAMA????MAZON????????";
char p[]="AMAZON";
printf("%s \n",S);
int i,j,flag=0;
i=i=strlen(S)-1;
while(i>=0)
{
int k=i;
for(j=strlen(p)-1;j>=0;j--)
{
if(S[k]==p[j] || S[k]=='?')
{
k--;
flag=1;
}
else
{
flag=0;
break;
}
}
int m=i
if(flag==1)
{
for(j=strlen(p)-1;j>=0;j--)
{
if(S[m]=='?')
S[m]=p[j];
m--;
}
}
else
{
if(S[i]=='?')
S[i]='A';
}
i--;
}
printf("%s",S);
}You are given a text file which contains all valid english words.(huge one).
Now consider a typical mobile keypad in which letters (a,b,c mapped to number '2', and d,e,f mapped to 3..w,x,y,z mapped to 9).
give an algorithms that gives all valid words given a 'n' digit number.
i.e. your given
the following mapping
abc -- 2
def -- 3
ghi -- 4
jkl -- 5
mno - 6
pqr -- 7
stu -- 8
wxyz -- 9
And huge text file with all valid words
write a method
String[] getAllValidWords(String number);
e.g. input 228.
output .: BAT, CAT, ACT, ..etc.
discuss the time and space complexity for your algo.
How would you implement an infinite counter?
Intersection of two lists of unsorted integers.
Give two ints, return index(0 based) of an int if it is present in another int. For eg. int a = 34, int b = 12345. Function must return 2 since 34 starts in 12345 at index 2.
Given a UNORDERED tree and two node elements, we are suppose to find the common LEAST ancestor if present from the given tree.
Given sorted integer array and a given value we have to find two elements which will sum up to a given value. Test all corner cases with minimum complexity.
An array of size N is given. Array is sub divided into sub array of size K. Find maximum value of each sub array.
My ans-
While traversing the array keep on adding values to max heap of size K and keeping a virtual window of size K on array.
When element leaves the window then remove the leaving element from heap too and reheapify the heap. And max element of that window will be again on top in heap.
Any better approach?
Suppose u have a square matrix of 0s and 1s only ... find the longest path of 1s available in the matrix and return that .. you can only move right and down ... For e.g.
0 0 0 1 1
1 1 1 0 1
0 1 1 1 0
0 0 1 0 0
1 1 1 1 1
Given a node of Binary Tree . find all node's at distance k from it .
You have a web server's log that records for each user the URL that he accessed.
Example format:
Time-stamp User-id URLHow to find the maximum common (sub)sequence of visited URLs from all users? Write code in java
Log entries are ordered based on timestamp.
Example log (omitting timestamp for clarity):
John URL1
John URL2
Jim URL2
Mary URL1
John URL4
etc
Update:
Example:
User-id URL
186 A
187 B
186 C
188 B
186 C
187 A
186 B
188 A
188 C
189 A
189 D
187 C
189 B
186 A
187 C
189 A
189 CSo the max common URL sequence is A,C,C (URL A followed by URL C, followed by URL C)
given a binary tree and a leaf node.
holding that leaf node and whole tree falls down such that it is the new root of the tree.
return the modified tree.
Find if the given two trees can be joined leaf to leaf?
program to find all prime numbers in the range of
the input start/end numbers.
start number: 1,000,000,000,000
end number: 1,000,000,000,000,000
suppose i m sitting on a server and several machines are pinging me with a word each and we are storing these words in a Queue.Now,the data stored in the queue is very large and we can process it once only.At the end of the day we are given 5 words and we have to find all the anagrams(for each of the 5 words) present in the queue.
Design Online Movie Booking System.
Describe ACID properties in terms of a database transaction
Database server is in US and web server is in India, how will you handle time zone conversion?
Given two arrays of integer, print out the values from first array which are not present in second array. Time complexity should be O(n)
Given a BST, how would you return the nth smallest element. The code had to cover all the edge cases and was expected to write a logn solution
How does a site like Facebook store "Likes" ?
Whats the best approach for Space complexity and Time complexity ? Can we do it in O(1) space or at least O(n) space ?
Given a Binary Tree (not BST) with integer values . 1) Find path from root to any node with max sum. 2) As there can be many path's find all of them. 3) Print all such paths.
Do this in O(n) : n is number of node's in tree. he wanted an O(n) solution not O(n)+O(n) ie. u can't traverse tree twice .
Classic 2-sum problem.
Hint, using hash table.
Implement atoi().
Select a random node data from a very long linked list whose length is not known such that the probability of each node is equal.
Large shared HDD is synced with Cloud Server. HDD contains same files multiple times by different users. How does the cloud server manage duplicates. It can't store all the duplicates. Duplicates may not be differ by file name. Discuss algorithm.
Print all valid phone numbers of length n subject to following constraints:
1.If a number contains a 4, it should start with 4
2.No two consecutive digits can be same
3.Three digits (e.g. 7,2,9) will be entirely disallowed, take as input
The producers write elements to a ring buffer(fixed size) while the consumers access elements from it. Implement a write and a read function using a producer pointer and consumer pointer. The consumer pointer cannot surpass the producer pointer and when the producer pointer reaches where it starts again, it stops.
Given a file, we have to replace a word with another word.
Design online movie ticket booking system.
Given 2 arrays, with less complexity you have to tell me both the arrays contain same elements or not.
array 1 = {1,4,3,8,2,8}
array 2 = {}3,5,1,2,6,8,3,4}
there are two arrays named A and B , both of them with k size, they are sorted in acsending order. could you find k-th smallest combinations of ai, bj -->(ai+bj) . 0<=i,j <k.
for example: a = {1, 3, 6} b = {4, 5, 6} then we will get 1 + 4 = 5, 1 + 5 = 6, and 1 + 6 = 7,the result is 5,6,7. does it make you understood? and could anybody do it with less time and space complexity.
Hi guys, thanks for all your suggestions and idea, and finally I get my answer and here are my c++ codes, time complexity is O(k*lgk), and space complexity is O(k):
#include<iostream>
using namespace std;
typedef struct node{
int row;
int col;
int data;
}Node, *PNode;
void swap(PNode &a, PNode &b) {
PNode temp = a;
a = b;
b = temp;
}
void adjust_min_heap(PNode *bin, int i, int k) {
int left = 2 * i + 1;
int right = 2 * i + 2;
int min_index;
if(left < k && bin[left]->data < bin[i]->data) {
min_index = left;
} else {
min_index = i;
}
if(right < k && bin[right]->data < bin[min_index]->data) {
min_index = right;
}
if(min_index != i) {
swap(bin[i], bin[min_index]);
adjust_min_heap(bin, min_index, k);
}
}
void build_min_heap(PNode *bin, int k) {
for(int i = k / 2; i >= 0; i--) {
adjust_min_heap(bin, i, k);
}
}
int *get_k_th_minimum(int *a, int *b, int k) {
PNode *bin = (PNode*)malloc(sizeof(PNode) * k);
int *result = (int*)malloc(sizeof(int) * k);
memset(result, 0, sizeof(int) * k);
int i;
int count = 0;
for(i = 0; i < k; i++) {
bin[i] = (Node*)malloc(sizeof(Node));
bin[i]->row = i;
bin[i]->col = 0;
bin[i]->data = a[i] + b[0];
}
build_min_heap(bin, k);
while(count < k) {
result[count++] = bin[0]->data;
bin[0]->col += 1;
bin[0]->data = a[bin[0]->row] + b[bin[0]->col];
adjust_min_heap(bin, 0, k);
}
for(i = 0; i < k; i++) {
free(bin[i]);
}
free(bin);
return result;
}
void main() {
int a[] = {1, 2, 4};
int b[] = {5, 9, 11};
int k = 3;
int *p = get_k_th_minimum(a, b, k);
for(int i = 0; i < k; i++) {
cout << p[i] << " ";
}
free(p);
getchar();
}
given an array [1,2,3,4,5]
give out all non repeating combinations of size 2. generalize it for any size
find least common ancestor in btree.
Note:its btree not bst
find all broken links in a web page
how to implement LRU for ecommerce site --> use linklist+map
How will you store friend-to-friend relation of facebook in db
Given a polygon with N vertexes and N edges. There is an int number(could be negative) on every vertex and an operation in set(*,+) on every edge. Every time, we remove an edge E from the polygon, merge the two vertexes linked by the edge(V1,V2) to a new vertex with value: V1 op(E) V2. The last case would be two vertexes with two edges, the result is the bigger one.
Return the max result value can be gotten from a given polygon.
I 've table book containing 2 columns
title and price
there are a number of books there with different prices
what is result of the following query
select title from book as b where (select count(*) from book as t where t.price>b.price) < 5
Suppose there is a distance matrix which consists of n points and that gives the distance of say (a,b) = 6 , (a,c) = 5. If there are N points assume 10000, then it requires N * N matrix to store the corressponding distances.How to store the matrix in such a fashion that it gives a fast retrieval and optimized storage.
3.Find the first unique character in a Stream. Please note that you are being provided a stream as a source for these characters.
The stream is guaranteed to eventually terminate (i.e. return false from a call to the hasNext() method), though it could be very long. You will access this stream through the provided interface methods.
A call to hasNext() will return whether the stream contains any more characters to process.
A call to getNext() will return the next character to be processed in the stream.
It is not possible to restart the stream.
If there is no unique character, then return the character '#'. # won't be any character in the character stream.
You just have to complete the function getUniqueCharacter() using the functions hasNext() and getNext() which are already defined.
Example:
Input:
aAbBABac
Output:
b
Input:
aBBa
Output:
#
2.Given an integer linked list of which both first half and second half are sorted independently. Write a function to merge the two parts to create one single sorted linked list in place [do not use any extra space].
Sample test case:
Input: List 1:1->2->3->4->5->1->2; Output: 1->1->2->2->3->4->5
Input 2: 1->5->7->9->11->2->4->6; Output 2: 1->2->4->5->6->7->9->11
C/C++/Java/C#
struct node
{
int val;
node *next;
}
node* sortList(node* list1) {
}
Java
class Node
{
int val;
Node next;
}
Node sortList(Node list1) {
}
1.You are given a function calcDifference which takes in the root pointer of a
binary tree as it's input. Complete the function to return the sum of values of nodes at
odd height - sum of values of node at even height. Consider the root node is at height 1
/* Write your own custom functions here */
int calcDiff(node * root){
/*
struct node {
struct node *left,*right;
int val;
node(int x){
val = x;
}
};
typedef struct node node;
The structure is already declared, you can just start initializing nodes
*/
}
Input a series of points. If there are 2 points, draw a line. 3 points: draw a triangle, 4 points: draw a square. The trick part is(the interviewer said this), implement redo/undo functions.
Implement a method for a web service call that receives a collection of n coordinate points and returns
the kth closest point to the origin (0,0). For example, if k=1 the closest point to the origin should be
returned. If k=n the furthest point from the origin should be returned. (Use Divide and Conquer Approach looking for implementation in Java)
Given a dataset with three columns: one column shows the account number from which an amount of money is wired, one column shows the account number to which the amount of money is wired, and three shows the amount of the transfer. Design an algorithm to make a new dataset with three columns such that the first column is the account number, the second column is the TOTAL amount of money transfered to the account, and the third column is the TOTAL amount of money transferred from the account.
You have a vending machine with some inventory. write a program to help vending machine tender exact change to the customer.
Find successor in a BST with duplicate values allowed.
Reverse Linked list in parts iteratively.
ex 1->2->3->4->5->6->7->8 and if 'parts' is 3.
o/p = 3->2->1->6->5->4->8->7.
nth size of array Push all the non-zero's of a given array to the end of the array. In place
Write a method that takes a camilCase string as a parameter and returns underscore_case as output. Assume that input can be null or empty. If CamilCase parametar starts with a capital letter turn it into lower case without puting underscore before it. How do you test this method?
Given a String "abcxrrxabcrr"
Find the first repeated string with minimum 3 character?
Answer is "abc" min 3 characters.
What is the difference between heap and priority queue?
What is its time complexity?
Time Complexity of array(both sorted and unsorted) and doubly linked list(both sorted and unsorted)?
What is the difference between overloading and overriding?
Given an int array sequence:
1
1,1
2,1
1,2,1,1
1,1,1,2,2,1
3,1,2,2,1,1
1,3,1,1,2,2,2,1
1,1,1,3,2,1,3,2,1,1
...
What's the rule of the sequence?
Given an other int array a[], how to determine if a is in the sequence?
Given a Tuple for eg. (a, b, c)..
Output : (*, *, *), (*, *, c), (*, b, *), (*, b, c), (a, *, *), (a, *, c), (a, b, *), (a, b, c)
program to reverse the words of the string?
i.e., if i give i am a girl the output should be girl a am i
Design a Restaurant Reservation system.
10 fishes are marked and left in a pond, 15 fishes were caught out of which 5 were marked. rest 10 were also marked and left in pond Calculate the minimum no. fishes in pond
Write an algorithm to evaluate the Postfix Expression
Implement the integral part logn base 2 with bit manipulations
very large bytestream (PB)
synchronization algorithm
given:
unsigned char read_byte(); ← side effect that it advances a byte pointer in the stream
write:
unsigned char read_sync_byte(); ← may result in >1 calls to read_byte()
remove byte '03' from the stream if the stream is in pattern 00 00 03
Example:
read_byte():
00 0f 42 17 00 00 03 74 00 00 00 00 14 ...
read_sync_byte():
00 0f 42 17 00 00 74 00 00 00 00 14 ...
Given 2 BSTs. Find the largest common bst between them.
WAP to print k closest points in a plane having n points (2D).
You have a sentence with several words with spaces removed and the words have their character order shuffled. You have a dictionary to lookup. Write an algorithm to produce the original sentence back with spaces and words with normal character order
You have a two dimensional array of size m*n. The
elements in the rows are sorted and every row has
unique elements means( in a row no two elements are same) but
the elements can repeat across the rows.
For example:
you have following 2-D array:
{
2 5 7 9 14 16
3 6 8 10 15 21
4 7 9 15 22 35
7 8 9 22 40 58
}
You are supposed to write an efficient function which
will take upper 2-D array as input and will return a
one-dimensional array with following properties:
a) the 1-D array must contain all the elements of above
2-D array.
b) the 1-D array should not have any repeated elements.
c) all the elements should be in sorted order.
For example:
for the above 2-D array, the output should be:
A [ ] = { 2, 3, 4, 5, 6, 7, 8, 9, 10, 14, 15, 16, 21, 22, 35,
40, 58 }
Function Prototype should be :
int [ ] MergeAndSort( int[ ][ ] inputArray )
you r given an array and you have to find out the top 3 repeated numbers.
for e.g. RAM[] ={20,8,3,7,8,9,20,6,4,6,20,8,20}
so the output will be : 20 is repeated 4 times , 8 is repeated 3 times, 6 is repeated 2 times .
complexity must be best
I have an array of size N integers from 0 to n-1. Exactly one of them occurs odd number of times(instead of some other integers). Find that number in O(N) running time and O(1) space complexity.
I am pretty sure i would have to use bitwise XOR. But doing that will just give the XOR of all distinct integers.
differences between integer and int
given stream of integers? find first 100 large numbers
how garbage collector works in java
what is virtual binding?
What is deadlock? example
Given file tokens find common token?
A binary tree is given with left and right populated but the nextRight pointers in each node are not populated. Populate the nextRight pointer in each node.
1. There are a cluster of stateless servers all serving the same pages. 2. The servers are hosting 5 web pages- p1.html, p2.html, p3.html, p4.html and p5.html 3. p1.html just redirects users to the other 4 pages 4. Requests to p1.html should result in 10% of users being redirected to p2.html, 5% of users redirected to p3.html, 20% of users redirected to p4.html, and 65% of users redirected to p5.html. 5. Users do not need to stick to the page they are first redirected to. They could end up on a different page with every request to p1.html 6. Write a function/pseudocode that would be invoked with every request to p1.html and redirect the correct percentage of users to the correct page.
You are given a squared integer matrix of nxn size in which all rows and all columns
are sorted in ascending order. The task is to check if the given matrix contains a given key.
Give a min and max of an integer array, write a function to randomly return a number inside of this range, but not in the list. Also write a class that contains this function.
We define C(n) as the number of ways to take n identical objects out of a bucket, where objects may be taken 1, 2, or 3 at a time.
Example: C(4)=7, because you can take 4 objects in the following 7 ways:
1,1,1,1
2,1,1
1,2,1
1,1,2
2,2
3,1
1,3
Write a function for C(n) in the language of your choice.
How would you define a data structure that stores a set of values (i.e., a value cannot appear more than one time), and implements the following functions:
add(p)--adds the value p to the set
delete(p)--removes the value p from the set
getrandom()--returns a random value from the set (all items should be equally likely). (Assume you have access to some nice random() function.)
Need not write actual code, just sketch a structure to implement this efficiently.
Implement a bucket fill function for a bitmap image. Assume your bitmap image is a 2-d array of integers, where each integer corresponds to a different color. bucketfill should take three inputs, newcolor, x, and y, and change the color to newcolor in the largest contiguous monochromatic region containing the point (x,y)
Write a program that reverses alternate elements in a given linked list input: a->b->c->d->e, output should be b->a->d->c->e
Given two strings find if they are anagrams or not.
eg.
"tom marvolo riddle" and "i am lord voldemort".
(The example added the other constraint that the whitespaces donot matter.)
given an array of size n, it holds distinct integers from 1 to n. Give an algorithm to sort the array? one way is to just assign a[i]=i in the array. how to sort the array using the elements of the array and not just assigning directly
Given an integer, i, find whether it can be expressed as 2^k. Where k< i
Given an array say [9,20,-2,-45,23,5,1], find the minimum positive missing number from the array.
The answer in this case will be 2.
What is difference between oops and ooad?
Round 3 :
Q 6 : You are given a ternary tree (a tree with 3 children at max with left, middle, right pointer at each node), create a singly linked list from it without using extra space ?
Round 3 :
Q 5 : You are given a binary search tree, and a value(data item), you need to tell the left most right cousin in as minimum time and as minimum space ?(need to minimize actual time complexity, he need minimum order of complexity as well as number of node access should be minimum)
Round 3 :
Q 1 : How are you ?
Q 2 : Do you want to go for MS or PHD ?
Q 3 : What type of branch is yours ?(actually my branch name is mathematics and computing, and after 3 year Microsoft allowed our branch to appear for placement, so they ask this question)
Q 4 : One question is from my project “Garbage cleaner Robot” ?
Round 2 :
Q 3 : you are given some nodes, and for each node a probability is given which will tell its importance, you need to design an efficient data structure such that the expected search time as minimum as possible. (Hint : Use dynamic programming + binary tree).
Round 2 :
Q 2 : You are given finitely many intervals in 1D, you have to design a data structure an efficient data structure which can answer queries of the form “In how many intervals the point P belong ?”, P is an input point, and all intervals are closed. I answer B tree(think why) which is most efficient.
Round 2 :
Q 1 : You are the supervisor of an airport. What happens is that visitors are not visit your airport, instead they go to another one, which means your airport become unpopular nowadays, Now as a supervisor you need to find out what has happens ?, What went wrong ?,How do you find out ?, What is correct ?, How do you find correct one and at what cost ?
Round 1 :
Q 3 : What do you think, how the posts in Facebook are shown, to your page, as there are thousands of posts, likes, videos, images, links etc. shared by your friends, but not all are shown to you ? (Data mining question, have to tell appropriate solution which can work ?)
Round 1 :
Q 2 : longest palindrome in a string ? (Need to tell in O(n) time complexity + O(1) space complexity)
Round 1 :
Q 1 : When you visit on your friend’s Facebook profile, there is a mutual friend section where common friends are listed, now let’s assume that your friend do the same thing, he/she visit his/her friend other then you, now the people other than common are connected to you by distance of two. Similarly think you are given two people on Facebook, how do you find this connectivity?. (Please give appropriate solution),
Now let’s think that some important people are given some weight(any), now do the same thing ?
Now calculate the most influential person? (Not an easy question, because of weights) ?
No coding, just was asked to tell how I would do this:
Adding a new part to the webpage that shows recently viewed items.
Questions: What items would you put in the web page?
How would you design the data structure?
How many items should be put on the list?
What would be size in bytes if we store 10 items per user?
Discuss other issues.
Implement a cache that stores a fixed amount of data, provides random access to the elements and is circular (like after completely filling a cache array, overwrite policy is overwriting the first item, then the second item and so on)
Given: A tree in which each node has a pointer to its parent and two nodes.
Print path for each of the two nodes from node to root.
If path for one node is partially same for the second node then only print the part of the path that is not same.
Do zigzag level order traversal of a BST
Find the nodes at d distance from a certain node in a Binary Tree
Find the largest number obtained by rearranging the digits in O(n) time.
Why C language does not support column major array?
How mb differ from wmb in Linux? Is mb equal to wmb & rmb ?
Design a data structure for LRU where replacement can take up to O(log n ) time, searching take O(log n) time, inserting will also take only O(log n) time(Big question, I was given some time(around 5 to 10 minute) to think) ?
What is virtual memory, how operating system uses it ?
How can we reduce search time in linked list(reduce time complexity to O(log n), it is not given but I gave my answer with O(log n) complexity) ?
Draw a simple model of a Program Control Block ?, Now write a simple code and show all the sections in the code (means when this code will run then which section of the code go where in PCB) ?
Print a binary tree without using recursion(inorder print) ?
Given a BST, with nodes having a parent pointer, a pointer to a node (any node), and a value. Find the path from the given node (pointer), to the node with the given value.
Find the element that appears once
Given an array where every element occurs three times, except one element which occurs only once. Find the element that occurs once.
Expected time complexity is O(n) and O(1) extra space.
Examples:
Input: arr[] = {12, 1, 12, 3, 12, 1, 1, 2, 3, 3}
Output: 2
Given an input string , "this is apple ****" replace all occurences of "apple" with another word say "freedom" .The interviewer insisted on returning the modified string as an array. No input parameter for writing the output provided.Dont know how can an array be returned in c or cpp . Returning the pointer to a local array would definitely not work .
Please comment.
code to cmp two strings in two diffrnt text file.... in c....
How do you design a column database
ArrayList A, B, C are sorted int arraylists.
When A[i] + B[j] = C[k], you need to remove C[k] from ArrayList C.
Please implement code with O(N^2). Note that you are not allowed to use additional data structures such as arrays, hash tables, etc.
Difference between applets and application.
How do you implement sin, cos functions of a calculator?
Total number of steps are given (let N)
at a time you can take one or two steps..
Q total number of ways to reach N.
My Ans: find out total number of non -ve solution to the
equation X + 2Y = N
For every pair of value, find out total number of arrangement. Ex X = x and Y = y
then arrangement is (x+y)!/(x! * y!).
I think my answer is correct but interviewer was not convince.. may be he is looking some mugged answer ..
Build a key-value data structure which can perform following 2 functions
- lookup
- rangeLookup(key1, key2)
Given two string S1 and S2. S1 contains from A-Z and S2 contains A-Z, * and ?
Where * means any character 0 or any number of times
Where ? means any character 0 or 1 number of times
Write a program to determine whether S2 matches S1
Design a system where you can reutrn top 20 queries made in last 24 hours to users.
Think on the scale of Google and Yahoo. How would you store data. What will be your data structures, algorithm to get that data.Describe your assumptions etc.
For simplicity, you can assume that every web server create a log file with query and timestamp.
I've three tables : Employee,Department,Region as shown below:
Employee
EmpID, EmpName, Salary
101, 'Karthik', 10000
102, 'Amir', 15000
Department:
DeptID, EmpID, DeptName
3, 101, 'CSE'
4, 100, 'ECE'
Region
RegnID, DeptID, RegnName
10, 3, 'KL'
11, 9, 'DL'
Now i want to print all employee details according to the region (RegnName)they belong to.
given arr1 = {5,6,4,2,2} arr2={4,2,2,1}
return common elements {4,2,2}
HashMap h=new HashMap;
h.put(1,tom);
h.put(1,tom)
how hashmap deal with duplicate entries...
"What will happen if two different objects have same hashcode?”
Given a graph and asked to print some order which is BFS..so asked to implement BFS
and each node is of type person
class person{
int ssn;
String name;
}
c = ‘a’
w = “apple”
c covers w, iff w contains c.
c_set = {‘a’, ‘b’, ‘c’, ‘g’}
w_set = {‘apple’, ‘ibm’, ‘cisco’, ‘google’}
c_set covers w_set, iff every w in w_set is covered by some c in c_set.
Given c_set and w_set, Whether w_set is covered by c_set?
Follow up: if w_set is fixed say a book, how to determine whether a c_set covers this w_set?
For a given set of points find a point along with 3 others that are closest to each other.
find 10 most frequently occurring words in a given file.
Given a board of snakes and ladders game, provide an algorithm to find the minimum number of dice rolls required from 1 to 50 and maximum number of dice rolls required from 51 to 100.
Note: Consider snake bite and ladder up condition from the board.
Suppose you have given a tree with N nodes and weights associated with each node and edges are given(present in the tree).You have to remove two edges such that the sum of weights of three trees created is maximum.
Write a function to reverse the word order of String. Do this in-place. "This is a cat" -> "cat a is This". Spaces between words may not be consistent.
Given an NxN matrix with unique integers : Find and print positions of all numbers such that it is the biggest in its row and also the smallest in its column.
As kernel can access user space memory, why should copy_from_user is needed?
what are the best synchronization techniques used in linux kernel?
Write a program to read a give directory in your hard drive and list all the sub directories and files as hierarchy structure.
Write a program to shuffle a deck of 52 cards and shuffle them equally to 4 players
Write a program that takes an array of numbers, and then prints out all the possible pairs of numbers that sum up to the value N.
E.g., if the array contains the numbers {0, 1, 2, 2, 3, 4, 5} and the target value N is 4, then the output would be (0, 4), (1, 3), (2, 2).
EMP (empno, name, deptno, salary)
DEPT (deptno, name)
Write a SQL query that tells me the average salary by department name.
you have a matrix of N x N filled with 1 or 0. you can move only 1 step either right or 1 step down. you need to count maximum number of "connected 1" in given matrix. for example
0 0 1 1
1 1 1 0
1 0 1 0
0 1 0 1
[Start from top left] maximum no. of 1 is 4
[1,0][1,1][1,2][2,2]
design Malloc Function which user can call and get the allocation. For example, there is a Byte array of byte[1000] so if use call getAllocation(3) then we will assign 3 bytes to user. and again if another user call getAllocation(100) then we will assign again,
Which data structure and java design pattern are best fitted for Car Parking problem.
I have two threads, both contain data from a database table. One thread performs some operation and update the data in the database table whereas second thread has not yet done any operation. Second thread does operation after some time and wants to update the operation. Since the first thread has already updated the data in the database table, second thread has stale data. How can we manage so that table should have the actual data not the stale data.
int n=99;
int unsignedShift = n>>>2;
System.out.println("unsignedShift="+unsignedShift);
The above result gives "unsignedShift=24". The question is if 24 is given how can I get back the original value ie n ie 99. How to do it for both positive and negative integer. How to do it in java.
Create a class Graph, which must represent the graph data structure in java. What will be the difference between directional and unidirectional Graph? How would you represent the weight of the edges?
WAP to compare string without library function in c??
1)Program should be designed using Pointers
2)Most efficient i.e lesser number of loops or comparisons??
If we have a very big text file which contains millions of lines of code. On every line there is a one word. We also have a random generator which returns a number between 0 and 1. When we have 1 - this will corresponds to the last line of the file. When we have 0 - to the first one. We want an algorithm which tells as the word (the line) which corresponds to the generated number.
Write an algorithm to check if a tree is binary search tree
How will you convert a min heap to max heap (or viceversa) without using additional data structures??
Given the two arrays with integers, return the common elements
A soccer league has n matches with A,B,C teams with number of goals scored by each team in each match.If a team wins against another team ,It gets 3 points and lost team gets 0 point.If a tie ,both team gets 1 point.Now how do you frame the ranking of teams.
1) All teams played n matches.
2) A team 1 match,B Team 2 matches, 3 team 3 matches.Like wise it goes.
They looked for coding and data structure techniques.
A log file which has user details(user ID,timestamp) and pages visited in a particular day by that user.The next day -the same kind of log file gets generated.How do you find the probability of users who logged in consecutive days out of the second day - logged in users? The question is simple,but they look for the efficient data structure and time complexity.
Assume there's a website with 8 pages. We are interested in calculating the most frequently visited page sequences of size 3( e.g 1->5->2 ).We are given a log file that has several rows for a particular time period. Each row has following info : time, UserID, page visited
Suggest an optimal algorithm to find the most frequest visited page sequence of size 3.
In a circle there are N number of Gas filling stations which can provide you will gas of capacity C1, C2…CN. Distance between filling station is D1, D2, D3……DN. Considering your vehicle will consume 1 volume of gas per distance. Find the filling station from which you should start the journey so that you will never get short of Gas.
Develop a function which will return either true or false. But at any point of time it should not return more than N number of true (it can be less than N) in last X secs.
For a string with uneven number of white spaces, what is best method or algorithm to trim the white spaces between characters, except special characters like !or,
Also the beginning and end should not contain any white space
Given a 2D array of size m X n, containing either 1 or 0. As we traverse through, where ever we encounter 0, we need to convert the whole corresponding row and column to 0, where the original value may or may not be 0. Now devise an algorithm to solve the problem minimizing the time and space complexity.
Given a tree as below.
1
/ \
2 3
/ \ / \
4 5 6 7
/ \ / \ / \ / \
8 9 10 11 12 13 14 15
Create a linked list as follows:
1->5->6
2->9->10->12
3->11->13->14
4->NULL
8->NULL
7->NULL
15->NULL
how many ordered trees are possible with N nodes?
Given an initial word and a final word(both same length) suggest an algorithm to find if there were some intermediate steps to convert the initial word to the final word.
The word at every step should be just one character different from the previous word and should be a valid dictionary word.( E.g TAP -> TOP is allowed, since the only difference from previous word is 2nd character and TOP is a valid dictionary word , but TAP -> TOO isn't allowed since 2 characters are different).
Write a function that will return true if a circular singly linked list has duplicate values. For example, given a pointer to a node in the circular singly linked list, *slist, where the only values each node of this list contains int value, and *nxt_pointer. How would you traverse it and what way will allow you to have the best case for time-complexity? How would we know when the circular singly linked list stops?
What will be the minimum and maximum output of I
i=0;
threadA
{ i++;
i++;
i++;
}
threadB
{ i++;
i++;
i++;
i++;
i++;
}Array on integer is given
find out next bigger number
Ex {2,5,3,4,61}
Out: 2->5
5->6
3->4
4->6
6->-1 //not possible
1-> -1 //not possible
Given a Binary Search Tree, find the k-th largest value of the the tree.
Suppose you have some guests arriving at a party. For each guest, you are given the arrival and departure time. When a guest arrives he is given a wine glass and when he leaves he returns that wine glass (it becomes available to be given to another guest). Find the minimum number of wine glasses needed to serve all the guests. The arrival and departure team can only be between 1800 to 2359 hours.
Given a binary tree, such that each node contains a number. Find the maximum possible sum in going from one leaf node to another.
For each subject topic(like Maths,Physics,Java,Sql), I have some urls.
In each url,I have a list of questions.
Now on each click(lets say Physics),I shall hit all urls(which could be in thousands) and then parse through them to get all the questions and persist them to DB.
Please tell me what can be the high levl and low level design for this in Java(Explain patterns that cn be used,Threads etc...)
Write an algorithm to scan all anagrams in a word doc.
This should be done in minimum time possible.
I am given a third-party library with its header to use. Now this library has a class 'Base'. Problem with this class is that it does not have virtual destructor. Now since i don't have the thirds-party code with me i can not do changes over there.
I am told to write few derived classes with this and make sure that the object gets cleaned properly when objects are delete. How can we achieve this?
Why here output is not Derived Class????
#include <iostream>
using namespace std;
class Base {
public:
char* name;
void display() {
cout << name << endl;
}
};
class Derived: public Base {
public:
char* name;
void display() {
cout << name << ", " << Base::name << endl;
}
};
int main() {
Derived d;
d.name = "Derived Class";
d.Base::name = "Base Class";
Derived* dptr = &d;
// standard conversion from Derived* to Base*
Base* bptr = dptr;
// call Base::display()
bptr->display();
}
// OUTPUT
Base Class
We have table:
create table employee (id int, name varchar, salary decimal, mgr_id int);
We want to print name and salary of employees that make more than their manager or don't have a manager.
This can be done by the following SQL:
select name, salary
from employee e, employee m
where e.salary > m.salary and e.mgr_id = m.id;
Question: how to do this with Hadoop? Write down the function for the mapper and reducer respectively.
map: k,v -> (k’,v’):
reduce: k, <list v>, ->k’, v’:
suppose you have a string like-I am a king ,
in this string you have to write code to count the total number of words which have only single alphabet .for this string answer sholud be 2.
Given pointer to the bytes array on size N that represents big integer "a" and 2-bytes integer "b" implement mod (%) operation for them: a % b
public class Finder {
public static void main(String[] args){
System.out.println(X.Y.Z);
}}
class X{
static class Y{ static String Z ="Apple"; }
static W Y = new W();
}
class W{ String Z = "Orange";}Please give the output with proper reason.
In a BST, write a function to find two nodes whose sum is equal to a given integer 'k'.
represent a n-ary tree with a data structure.
and also check whether tree has a cycle or not?
How to find length of a singly linked list with loops??
How can you efficiently implement three stacks in a single array, such that no stack overflows until there is no space left in the entire array space.
write code in java /c for expression 5+4*(7-15) or have parenthesis in any order .
Let's say you have to make changes to 1000 API's. For example, currently developers need to put a .then() just to write something to the screen; we want to remove this in simple cases, but also enable it in cases where you really do want to write something only AFTER some other action has taken place.
These 1000 API's are split among 200 teams, and you're a product manager for one of those teams.
How do you go about pushing for this change, so that eventually all of them will be changed?
How long would it take? What is the deadline?
What if one team simply says they're far too busy?
And once the dev teams are done with the changes, what more is there to do? What should the testing team do?
Given a list of words, return a list of lists, where each list contains a group of anagrams.
Sample Input: cat bat act tab
Sample Output: [ [ cat, act ] , [ bat, tab ] ]
Phonebook contains number and name.
1.use the java collection to add these entry (name and string).
2.Search the name by number
3.Remove the entry (name and string ) by using name.
I need to do this in Java...But if you can suggest me some Collection that can be used here, I shall do that....
I thought of :
1.using Hashmap,but here both name and number will be key....which wont be good...
2.Another option is to wrap both phone and number in an object and then add them to the list.And then Iterating and adding to the list.
Any other suggestions..?
Print below series in java
*** 1***
**2 *2**
*3*3*3*
4*4*4*4
Write an efficient code in c to implement the words in dictionary order.
Design algo for insertElement, deleteElement and getRandomElement, expected complexity for all the operations will be less than O(n).
I have one bag of bolts and another bag of nuts, need to find biggest Bolt. Condition is must not compare both bolts or both nuts. only comparison between bolt and nut allowed.
Given a node with pointers to its Parent, Child and the right Sibling, implement code to find the node to the right of a given node, at the same level. Assume it's a binary tree.
Given the string of parentheses only, write the function to check if they are balanced. ((())) is balanced, )( is not.
Follow up: Now the string also contains curly and square braces. You already have boolean functions, isOpenBrace() , isCloseBrace() and bracesMatch(char brace1, char brace2) as required. How do you check if braces are balanced?
write an algorithm to shuffle a play list (list of music titles); a random number generation function is provided which will generate a number between two given numbers (included). However, repeated call to the random number function is not guaranteed to return unique numbers; i.e., random sequence is not unique.
find the first non-repeated character in a string.
Given two arrays, write a program to merge them to a new sorted array ? and give test cases..
Write a program that finds whether the two binary trees are mirror image of each other?
#include <iostream>
#include <stdio.h>
using namespace std;
class A{
public:
void fun(int& temp){cout<<"am inside fun()"<<endl;
temp = 2000;
printf("in fun() temp[%p] temp val[%d]\n",&temp, temp);
}
};
const int temp=100;
int main()
{
A a;
printf("in main() temp[%p] temp val[%d]\n",&temp, temp);
a.fun(const_cast<int&>(temp));
cout<<"temp:"<<temp<<endl;
}Questions:
1> when i run this pgm @ line "temp=2000;" pgm will crash. what is the reason for sigsegv in this case?
2> if i make const int temp=100; declaration inside main() then, no crash and value change (i.e. temp=2000;) persists only inside fun(). But in the scope of main() this changed value is not seen. whats happening here? But address of temp in both the cases shows the same!! how is this possible??
write code to find the height of a character which is written on the m*n Grid. where 1 denote the character on the grid.
Tree with black and white nodes is given. Find a longest path of white nodes in the given tree.
Implement your own API and library for a synchronization OS problem.Write your own semaphore.
Eg: Capacity of TAM is 5 .. Queue of people outside is 100. Synchronization reqd.
Implement queue using stacks.
Delete the nth last element from a singly linked list. Don't count number of nodes initially.
The dynamic-set operation UNION takes two disjoint sets S1 and S2 as input, and
it returns a set S = S1 U S2 consisting of all the elements of S1 and S2. The
sets S1 and S2 are usually destroyed by the operation. Show how to support UNION
in O(1) time using a suitable list data structure.
Implement a bus reservation system asume bus' seats are as follows
HHHHHH
HHHHHH
HHHHHH
. . . . . . . .
you can assume 10 rows in bus.
Now if user enters 4 as required seat no then the prefrence order would be
4
3,1
2,2
2,1,1
1,1,1,1
and the function should return the seat number.
Given An Array with N integer with values ranging from 1 to N. there is only one duplicate in the Array.
Find out Duplicate value.
i.e.
A = { 10,6,3,4,7,5,2,4,9,1}
values from 1 to 10.
in this example, Duplicate element is 4.
N could be quite large.
You do have two linked list L1 and L2. The size of linked lists is huge and in billions. Linked List contains numbers (both negative and positive). For simplicity you can assume they are all integers.
You have been given a number say N. now you need to find out all of the pairs where one element from L1 + one element from L2 = N.
i.e.
L1 = 28, -7, 0, 56, 6, -8, 0, 72, 1000, -33
L2 = 53, 20, 27, -52, 99, 14, -8
N = 20
The answer will be:
(28, 8), (-7, 27), (0, 20), (6, 14), (0, 20), (72, -52)
more questions at http://dsalgointerview.wordpress.com/
Find the lexicographic rank of a string in the list of permutations of all characters of that string.
Find the first missing number in an array of sorted numbers.
Eg: Input : 4,5,6,7,9,11,14,18,19
Output : 8
Expected complexity : O(log n)
Approach is similar to binary search
Write a function to calculate the difference between the sum of all nodes' value at even and level of a Tree.
Write a function to sort linear Linked list without using extra memory.
Reverse word in the string
Find the least common ancestors for two tree node. Given the parent point.
Given two arrays, array1 and array2
using the rule of array1 to sort array2.
Ex.
array1 = { B, A, C}
array2 = {A, B, A, C, A, B, B, C, A}
output: sortedArray2 = {B,B,B,A,A,A,A,C,C}
What if array2 existed some element not existed in Array1? Can you put it in the end? and sorted by alphabetical? What if array have lower case and upcases letter?
Got FB interview questions is not difficult, basically, he is asking to count number of identical chars in a given string with with some special case handling, and return the number with highest count, question is pretty long leaving you to dig an algorithm.
Etc, given string "coffee tuffee", should return 4.
I was having my usual interview brain freeze, and start doing initializing with int, how silly
well after interview when I cool down, it doesn't take long to figure out as code below, little over weighted algorithm but the most concise I can wrote, someone please give more efficient code.
def parseword(a_word):
a_word=a_word.lower()
count=list(map(a_word.count, a_word))
return (max(count))Given a string we have to find first non-repeating character in the string....
Example: str="aabbbccccddeffffgg";
Answer is : e
Write a function to check whether the two strings are rotation of each other or not.
Example: str1="Password" str2="ordPassw"
My Solution was.........
#include<stdio.h>
void fn(char * str1, char * str2)
{
int i=0, j=0,flag=0;
while(str2[i])
{
if(str2[i]== *str1)
{
flag=1;
break;
}
i++;
}
if(!flag)
{
printf("2nd String is not a rotation of other\n");
return;
}
j=i;
while(str2[i])
{
if( !(str2[i]==*str1))
{
printf("2nd String is not a rotation of other\n");
return;
}
i++;
str1++;
}
i=0;
while(i<j)
{
if( !(str2[i]==*str1))
{
printf("2nd String is not a rotation of other\n");
return;
}
i++;
str1++;
}
if(*str1=='\0')
printf("String are rotation of each other\n");
else
printf("2nd String is not a rotation of other\n");
}
int main()
{
char * str1="Password";
char * str2="ordPassw";
fn(str2, str1);
return 0;
}given two ascending sorted arrays, how to combine the two arrays into one sorted array.
given 3 by 3 matrix ( all the entries are 1,2,3) defining 9 multiplication relationships. e.g Matrix(1,2) = 1 means 1*2 = 1.
For a sequence 112333222111, determine wether you can put parentheses on it to make it equals to 1?
You are given a grid of numbers. A snake sequence is made up of adjacent numbers such that for each number, the number on the right or the number below it is +1 or -1 its value. For example,
1 3 2 6 8
-9 7 1 -1 2
1 5 0 1 9
In this grid, (3, 2, 1, 0, 1) is a snake sequence.
Given a grid, find the longest snake sequences and their lengths (so there can be multiple snake sequences with the maximum length).
A pxq size matrix is given, and a matrix of size axb is removed from top right corner. Find the total no. of paths from top left to bottom right, with only right and down movements allowed. No path should go into the removed matrix.
eg-
_
|_|_
|_|_|
this is (2x2) matrix after removing (1x1) matrix from top right corner. no. of ways - 5.
The algorithm should be fast enough.
There are 100's of html files in a folder. The files contain phone numbers in formats xxxxxxxxxx, xxxxx-xxxxx, xxx-xxx-xxxx. Have to search all the files and return unique phone numbers from those files.
Implement memmove .
Dont use extra memory.
How to optimise it further?
generate permutations of a string without duplicates and without using hashtable to memorize the permutations.
Given two singly linked list, find if they are intersecting. Do this in single iteration. Also find the intersecting node in O(n) time and O(1) space. By intersection I mean intersection by reference not by value
write insert method to insert a node into sorted circular linked list (Sorted based on int value). insert method takes 2 arguments, one is value to be inserted and other is reff to any random node in the sorted circular linked list
An array of building coordinates (x-axis point from origin,height,width) in units were given as an input. Buildings can overlap. We have to give the side view as an answer. Input will be given in sorted order based on x-axis point.
Ex : Draw rectangles based on the given co-ordinates to understand the problem better.
i/p : (5,10,25),(10,20,15),(15,5,5)
o/p : 5R 10U 5R 10U 15R 10D 5R 10D
means draw line 5units Right 10units Up 5 units Right ...
here
R-right, U-up , D- Down
the o/p should be in such a way if we follow that, we should be able to draw side view of those buildings.
Expected better than O(n^2) solution.
Just came from interview. The interviewer asked me this question: copy tree with unlimited number of children with breadth fist search...
Given an array of pointers to some nodes in a doubly linked list, find the number of connected node blocks the pointers point to.
This was at a recent written test...
There is a toycar placed on a 5 by 5 board.We can give 5 commands to it ,
PLACE(X,Y,F) where x denotes X Axis,y denotes Y Axis and F denotes the direction to which its facing.
MOVE->Move will move the toycar one step in the direction where its facing
LEFT->Left will turn the toycar by 90 degrees to its left and face it to the new direction .Note:Left will not move the toycar, it will just change the direction
RIGHT->Right will turn the toycar by 90 degrees to its right and face it to the new direction .Note:Right will not move the toycar, it will just change the direction
REPORT->Report shall tell me the X Axis,YAxis and Direction of the toycar. like 0,0,NORTH
Note:You cannot move,left,right,report the toycar unless you place it.
Assume its a Prod level code, Solve it in Java only.
Below is my code and I haven't been selected, please tell me if there is better way to do it because my solution is correct but probably very basic.Thanks.
package com.ds;
public class ToyCar {
private ToyCar toycar;
private boolean isToyPlaced;
private int xAxis,yAxis;
private enum Direction {EAST,WEST,NORTH,SOUTH};
private Direction direction;
public int getxAxis() {
return xAxis;
}
public void setxAxis(int xAxis) {
this.xAxis = xAxis;
}
public int getyAxis() {
return yAxis;
}
public void setyAxis(int yAxis) {
this.yAxis = yAxis;
}
public Direction getDirection() {
return direction;
}
public void setDirection(Direction direction) {
this.direction = direction;
}
ToyCar(){
}
public ToyCar(int xAxis,int yAxis,Direction direction) {
this.xAxis=xAxis;
this.yAxis=yAxis;
this.direction=direction;
}
public void place(int x,int y, Direction d){
if(x<0||x>5||y<0||y>5 || d==null){
System.out.println("Place Error:Attempt to place toy outside the box");
return;
}
toycar = new ToyCar(x, y, d);
isToyPlaced=true;
}
public void move(){
if(!isToyPlaced){
System.out.println("Move Error:Attempt to Move Toy without placing in board");
return;
}
if(toycar.getDirection().equals(Direction.EAST)){
int newPosition=toycar.getxAxis()+1;
if(newPosition<0||newPosition>5){
System.out.println("Move Error:Attempt to place toy outside the box");
return;
}
toycar.setxAxis(newPosition);
}else if(toycar.getDirection().equals(Direction.WEST)){
int newPosition=toycar.getxAxis()-1;
if(newPosition<0||newPosition>5){
System.out.println("Move Error:Attempt to place toy outside the box");
return;
}
toycar.setxAxis(newPosition);
}else if(toycar.getDirection().equals(Direction.NORTH)){
int newPosition=toycar.getyAxis()+1;
if(newPosition<0||newPosition>5){
System.out.println("Move Error:Attempt to place toy outside the box");
return;
}
toycar.setyAxis(newPosition);
}else if(toycar.getDirection().equals(Direction.SOUTH)){
int newPosition=toycar.getyAxis()-1;
if(newPosition<0||newPosition>5){
System.out.println("Move Error:Attempt to place toy outside the box");
return;
}
toycar.setyAxis(newPosition);
}
}
public void left(){
if(!isToyPlaced){
System.out.println("Left Error:Attempt to Move Toy without placing in board");
}
if(toycar.getDirection().equals(Direction.EAST)){
toycar.setDirection(Direction.NORTH);
}
else if(toycar.getDirection().equals(Direction.WEST)){
toycar.setDirection(Direction.SOUTH);
}
else if(toycar.getDirection().equals(Direction.NORTH)){
toycar.setDirection(Direction.WEST);
}
else if(toycar.getDirection().equals(Direction.SOUTH)){
toycar.setDirection(Direction.EAST);
}
}
public void right(){
if(!isToyPlaced){
System.out.println("Right Error:Attempt to Move Toy without placing in board");
}
if(toycar.getDirection().equals(Direction.EAST)){
toycar.setDirection(Direction.SOUTH);
}
else if(toycar.getDirection().equals(Direction.WEST)){
toycar.setDirection(Direction.NORTH);
}
else if(toycar.getDirection().equals(Direction.NORTH)){
toycar.setDirection(Direction.EAST);
}
else if(toycar.getDirection().equals(Direction.SOUTH)){
toycar.setDirection(Direction.WEST);
}
}
public void report(){
if(!isToyPlaced){
System.out.println("Report Error:How can i report when I am not on board");
return ;
}
System.out.println(toycar.getxAxis()+" , "+toycar.getyAxis()+" , "+toycar.getDirection());
}
public static void main(String[] args){
ToyCar to = new ToyCar();
to.place(0, 0, Direction.WEST);
to.left();
to.move();
to.report();
}
}Write a function that takes an array as an input and returns starting and ending indexes
within the array such that if we add elements from the starting and ending index we would get
maximum possible sum of any contiguous set of elements within that array.
how to Print elements of singly linked list in reverse without using recursion..
Print a binary tree in vertical order using singly linked list...complexity should be O(n)
Reverse words in a string
Ex:
Input : "This is a String"
Output: "String a is This"
Print Level order traversal of a binary tree in reverse way.
If tree is 1
/ \
2 3
/ \ / \
4 5 6 7
Output will be 4 5 6 7 2 3 1
Implement a method (in java) that takes an Iterator<T> iterator and an int sampleSize and returns a random sample no larger than sampleSize from the iterator.
Given a satellite picture with islands in ocean, how would you count the number of islands?
they request me to fix the error of install (they installed)
install ethereal?
this is error : http://www.kmasecurity.net/xforce/attachments/error-jpg.182/
Given a string like 01011011001, convert it to 00000111111 with best efficiency possible.
given a very large file with words. Reverse the order of all words. For Example: How are you doing today? -->>today? doing you are How I know you may say reverse the whole and reverse each word but, the interviewer said that the file is too big to fit into the memory and the file should be read through a inputStream object, then write the result file to harddisk.
U have a number, don't know how long it is, do not know how many digits, don't know when number ends, do not know which is the last number. There is a function to increment the number by 1, but function can take only stream of digits and not the complete number e.g if you have 878999 as a number, you could input this number into the function only as single digit e.g 8,7,8,9,9,9. The output should be the whole number incremented by 1 i.e 879000, remember only single digits you can send to function as input. You can use any data structure, but need to tell why you are using that particular data structure. No need to worry about Time complexity.
Kindly, suggest how to approach this problem ?
construct a BST given its preorder traversal. solution which i gave :-
make first element of array as node of tree and then if element is less than root and if greater then on right. but i got the answer right for the given example but i am not sure if it was right. can you please suggest me a method to do it.
Given a seria of points (Xi, Yi), find the line containing the highest number of points from the list.
Per my question he mentioned that I can assume that there is a given function that receives two points and returns the a and b of the line euqation (aX+b)
Write a function that returns a boolean value, if two strings(passed as input) represent the same algebraic equation, depending upon whether the strings are same or not. I guess, the length of both strings are equal, but not sure, and the operators involved are +, *, /, ^, (, )
Write a function to print out all permutations of a string.
I rephrase the original question as the following: Let say in Facebook, given two person A and B. Write a function to find out whether A is a friend or a friend of a friend of ... of B.
Give a rectangular matrix(order mxn), each cell having only 0's or 1's, find the largest rectangular sub-matrix with equal number of 0's and 1's in it. O(m^2 n^2) solution possible... More time efficient algorithm required... Is O(mn) possible?
How its possible to have only a specific Functionality as per the user Object should have , not all the functionality of the class to be loaded in object only user specific functionality?
How can we have an Abstract Class without any using any virtual Function in it ?
What is the difference between HashMap and Hashtable?
Why character array is better than string for storing password in java?
You have a log file with start/end times of different functions.
Find the total exclusive working time for a particular method foo().
E.g. Log:
(foo()_start, 10:01);
(foo2()_start, 10:03);
(foo()_start, 10:05);
(foo()_end, 10:08);
(foo2()_end, 10:12);
(foo()_end, 10:20);
Total time: (10:03-10:01) + (10:08-10:05) + (10:20-10:12) = 2 + 3 + 8 = 13
P.S. Recursion calls and inner calls of foo() are possible
I need to insert an element in a heap, making sure that it does not already exist in it. Can this be done in O(logn) time?
find longest palindrome in a given string, expecting time complexity must be less than O(n^2).
how function pointers are shared across different processes? using which iPCs?
what is binder in android?
is linux kernel a process / thread/ something else
Given a million points (x, y), give a O(n) solution to find 100 points closest to (0, 0).
Find the union of non-overlapping ranges,
e.g; given an array {0,3,1,5,7,9,8,13} where 0 is starting point and 3 is the end point and so on.
The output should be {0,5,7,13}
I have Created Dynamic Web Application...
there is user table with column "enabled" to check if the user is already logged in
enabled = true --> logged in otherwise not
if i logged in , i cannot loggin at the same time in anothe r browser ..
but if i logged in and close the browser, how can i handle further loggin ??
static HANDLE mutex[2];
static unsigned __stdcall threadFunc1(void *v){
while(1)
{
WaitForSingleObject(mutex[0], INFINITE);
if (k>=10)
return 0;
cout<<"\n\tWELL ThreadID : 1 : ";
cout<<GetCurrentThreadId()<<" :: "<<k++<<endl;
cout<<flush;
ReleaseMutex(mutex[1]);
}
return 0;
};
static unsigned __stdcall threadFunc2(void *v){
while(1)
{
WaitForSingleObject(mutex[1], INFINITE);
if (k>=10)
return 0;
cout<<"\n\tWELL ThreadID : 2 : ";
cout<<GetCurrentThreadId()<<" :: "<<k++<<endl;
cout<<flush;
ReleaseMutex(mutex[0]);
}
return 0;
};
int main()
{
unsigned int t1;
HANDLE h[2];
int *ii=&i;
mutex[0] = CreateMutex(0, 0, 0);
mutex[1] = CreateMutex(0, 0, 0);
h[0] = (HANDLE)_beginthreadex(0,0,&threadFunc1,(void *)ii,0,&t1);
h[1] = (HANDLE)_beginthreadex(0,0,&threadFunc2,(void *)ii,0,&t1);
WaitForMultipleObjects(2, h, true, INFINITE);
CloseHandle(h[0]);
CloseHandle(h[1]);
CloseHandle(mutex[0]);
CloseHandle(mutex[1]);
cin>>i;
return 0;
}
Output :
WELL ThreadID : 1 :
WELL ThreadID : 2 : 47124264 :: :: 01
WELL ThreadID : 1 :
WELL ThreadID : 2 : 47124264 :: :: 23
WELL ThreadID : 1 :
WELL ThreadID : 2 : 47124264 :: :: 45
WELL ThreadID : 1 :
WELL ThreadID : 2 : 47124264 :: :: 67
WELL ThreadID : 1 :
WELL ThreadID : 2 : 47124264 :: :: 89
why is output not syncronized ?
write a function to check given string matches with given pattern
Condition: only one wildcard used in the pattern, that is '*', but can be used in the pattern more than once.
Example:
pattern: *abc*def*.doc*
str: adsfabcxyzdefgh.docx
fucntion signature is like: boolean isMatching(String str, String pattern);
how sysctrl works?
how a function from one user process can be called in other user process?
mention 4 IPCs used in user level process in linux
write a program with 2 threads. one thread should print even and other should print odd numbers in sequence. how would you make it SMP safe?
below questions were asked to me:
1. explain device tree concepts in linux.
Given a tree with following special property, develop an algorithm to find the LCA of two input nodes. Only O(1) variables can be used.
property - all nodes have information only about their parents not their children.
Write a method to which will download a file from remote server
conditions are: if remote server not responding then should go into resume. Once it up it should start download file from where it got resumed.
write two separate methods,
1. read method to read file and
2. write method to write to file,,,
both must be thread safe and throughput (efficiency) should be high.
Print in spiral form as shown below
For n=2
3 2
0 1
For n=3
4 3 2
5 0 1
6 7 8
For n=4
15 14 13 12
4 3 2 11
5 0 1 10
6 7 8 9
given a set of coordinates (a,b), (d,e)... etc.
write a program to find Slope and Intercept of a line such that max points from those specified pass through the line.
given an array of positive integers and that you are allowed to change the sign of any of the integers whenever you require.
write a program to calculate the minimum sum of this array.
the sum should be >=0.
for example :
Array = {1,2,4,5} then sum = 0 as we change sign of 1 and 5{-1,2,4,-5}
Another Example :
Array = {1,2,4,5,6,17,20}, sum = 1 with {1,2,-4,5,-6,-17,20}
needed to turn a sequential Actions into parallel implementation
static string FlNm = Environment.CurrentDirectory, URL = "", TmpHtm = "";
enum Act
{
dolar, ValidateTimeOut
}
void Execute(Act Exc)
{
switch (Exc)
{
case Act.dolar:
URL = "http://www.boi.org.il/he/Markets/ForeignCurrencyMarket/Pages/Default.aspx";
FlNm += "\\TempHtm.htm";
TmpHtm = AgilityPacDocExtraction(URL).GetElementbyId("Dv_Main").InnerHtml;
File.WriteAllText(FlNm, TmpHtm);
break;
case Act.ValidateTimeOut:
URL = "http://hm.hental.co.il/timeclock/tcreportall/WorkDaysPerMonth.aspx?Cstate=Link";
FlNm += "\\TempHtm.htm";
TmpHtm = AgilityPacDocExtraction(URL).GetElementbyId("anyId").InnerHtml;
File.WriteAllText(FlNm, TmpHtm);
break;
}
}
public HtmlAgilityPack.HtmlDocument AgilityPacDocExtraction(string URL)
{
using (WC = new WebClient())
{
WC.Proxy = null;
WC.Encoding = Encoding.GetEncoding("UTF-8");
tmpExtractedPageValue = WC.DownloadString(URL);
retAglPacHtmDoc.LoadHtml(tmpExtractedPageValue);
return retAglPacHtmDoc;
}}
how to find the Third largest Element in an array of integers..? I suggested a logic using a buffer that can hold three elements..But it is of O(3n) complexity..Can someone give a better algorithm ?
There are two gates , one to hell and the other to heaven.
Two gatekeepers , one for each gate.
One of them always speaks the truth and the other always lies but you don't know which one s guarding which gate.
You are allowed only one question and you need to find out the gate to heaven.
What is the question you will ask and remember , you do not know which one speaks the truth and which one lies.
How can I give new implementation to methods in String.
For example: I need to give new implementation to concat method, which concats two string and convert to uppercase.
I answered that, i create new custom class and create a method concat and implement it as the way interviewer want, but he asked that he want to do for all the methods in String, so writing new implementation for a methods is not a feasible solution.
implement hasNext() and next() methods like the Java collection iterator's, but hasNext() checks if collection has negative value only, and next() only return negative (assume collection has intergers)
Given an array of positive and distinct integers, output all pythogrean triplets of them i.e They have to satisfy: a.a + b.b = c.c
// Finds and returns the value of the element that occurs an odd number of times
// in the input array. Examples:
// [1000000] => 1000000
// [2, 2, 2] => 2
// [1, 3, 3] => 1
// [1, 2, 3, 1, 2, 3, 4] => 4
// [1, 2, 3, 2, 1, 2, 3, 2, 1] => 1
// etc.
int findOdd(int[] input, int length) {
}
1. Remove the words where last character is a capital letter from a given sentence and then reverse the characters of each word
From a given a sentence, find the word which contains more than 1 vowels and print all special characters.
Input: This is a test sentence, good luck.
Output: Total words which contain more than 1 vowels: 2
The special characters are: , .
From a given string of numeric values, print the individual numbers in words separated by space.
Input: “2490”
Output: two four nine zero
Write a Java function to find unique integers of a given integer array. (Note: I assume the question won't allow using any Java Data Structures for unique elements. And the question might be for an array of characters instead.)
Here is a Java function API: int [] intersection(int [] a, int [] b). Provide your implementation of this Java function. (Note: it is an easy question. They are looking for code quality.)
There is a sorted array of infinite numbers (can contain duplicates). Given a number. Find the last occurring instance of that number in the array.
Ex., i/p: 12344445566667789...
search number: 6
o/p: 12 (index)
Difference between kill -9 and kill -3
How to find a process and kill in unix?
What is space complexity?
How to find time complexity of an algorithm?
What is Big Oh notation?
How inter-thread communication can be done?
How to improve query performance?
Difference between == and equals
Different ways to create/track session in web application?
Where do you prefer composite object vs interfaces?
What would you change about Java?
How to create Annotations?
What is GOTCHA in Java generic? Hint: Legacy code implementing collection
What would you change about Java?
Implement queue using stack
How to make object immutable?
Why do we need to override hashcode and equals methods?
What is MVC?
What are different isolation level?
How to desing log4j system?
why business logic shud not be written in stored procedure even though the database is accessible only to developer and no security issues(according to interviwer)?
why page load occurs first in aspx page the master page and then user control ????
1. You have a set of 10000 ascii strings (such as perhaps loaded from a file)
2. A string is input from stdin.
3. Write pseudocode that returns (to stdout) a subset of strings in (1) that contain the same distinct characters (regardless of order) as input in (2). Optimize for time.
4. Assume that this function will need to be invoked repeatedly. Initializing the string array once and storing in memory is okay . Please avoid solutions that require looping through all 10000 strings.
For example, if you have strings in (1): mary, brad, pitt, yygr
and the user types in: ry --> the output should be "mary" and "yygr"
or if the user types in: dd --> brad
very interesting.It's from cisco onsite interview.
write a function, and the output should be the function itself.
can anyone provide the code?
Given: a file with all possible words
Given: word like in Hangman game: H_L_
Output: getPossibleSolutions(“H_L_”) -> set contains strings “HELL”, “HELP”
You have a sequence S of n characters from an alphabet of size k <= n; each character may
occur many times in the sequence. You want to find the longest subsequence of S where all
occurrences of the same character are together in one place; for example, if S =
aaaccaaaccbccbbbab, then the longest such subsequence is aaaaaaccccbbbb =
aaa__aaacc_ccbbb_b. In other words, any alphabet character that appears in S may only
appear in one contiguous block in the subsequence. If possible, give a polynomial time
algorithm to determine the value of the optimal solution (i.e. the length of longest such
subsequence).
When i use the <input type="file"/> in HTML how do i save the complete path of the file chosen into a javascript variable
hi i am Louisborder on of interviewer given this question in written exam give me the explanation pls...
Given a tree with N nodes and weights associated with each node and edges are given(present in the tree).You have to remove one edge such that the difference of sum of weights of two tree created is maximum.
Supposed there are a large amount of datas in a large file(larger than 1TB), and much of them are duplicate. For example: {3,94,855,94,5323,94,....}. So, every duplicate one would have a frequency count. Design an algorithm, to find the data with the average frequency, the second highest frequncy?
Given a variable, how can you find whether it was allocated from stack or from heap memory???
we will name a number "aggregated number" if this number has the following attribute:
just like the Fibonacci numbers
1,1,2,3,5,8,13.....
the digits in the number can divided into several parts, and the later part is the sum of the former parts.
like 112358, because 1+1=2, 1+2=3, 2+3=5, 3+5=8
122436, because 12+24=36
1299111210, because 12+99=111, 99+111=210
112112224, because 112+112=224
so can you provide a function to check whether this number is aggregated number or not?
Write a program if given a series of alphabets followed by a numbers then output should be in the alternate order of alphbet followed by number.
Eg: abcd1234defgh8965 then output should be a1b2c3d4 d8e9f6g5 .
how to write case for the chat messenger application
draw the flow chart for an XOR cipher program using the
C programming language.
Your program must accept as input from the user a value between 0 and 255 to be used as the
secret key, the name of the input file and the name of the output file. No line in the input file
should contain more than 4096 characters.
After the user would have provided their secret key, your program should read and perform an
XOR cipher on the contents of the input file and write the result to the output file.
If the input file has already been encrypted and the identical secret key that was used to
perform the initial encryption is provided, then the contents of the output file should be
deciphered into its original plain text.
write the algorithm for an XOR cipher program using the
C programming language.
Your program must accept as input from the user a value between 0 and 255 to be used as the
secret key, the name of the input file and the name of the output file. No line in the input file
should contain more than 4096 characters.
After the user would have provided their secret key, your program should read and perform an
XOR cipher on the contents of the input file and write the result to the output file.
If the input file has already been encrypted and the identical secret key that was used to
perform the initial encryption is provided, then the contents of the output file should be
deciphered into its original plain text.
How to write an XOR cipher program using the
C programming language.
Your program must accept as input from the user a value between 0 and 255 to be used as the
secret key, the name of the input file and the name of the output file. No line in the input file
should contain more than 4096 characters.
After the user would have provided their secret key, your program should read and perform an
XOR cipher on the contents of the input file and write the result to the output file.
If the input file has already been encrypted and the identical secret key that was used to
perform the initial encryption is provided, then the contents of the output file should be
deciphered into its original plain text.
There are 3 person in a forest, when they slept at night someone from outside colored their faces black(all three). Now when they wake up in the morning all three started laughing at each other thinking that the other two persons have black faces.
But after some time they realized that their own faces are also black and then they stop laughing at each other.
Here, you have to give a valid LOGICAL REASON that how they realized that their own faces are also black, i.e. all three faces are black.
.
.
To mention here, these are not logical reasons... e.g.
1. They are looking on faces of each other so the other person will realize that his face is also black.
2. One will look into others eyes(eyes as mirror) hence he can find that his face is black.
3. He will use water to see his face if something wrong, hence he will find that his face is black.
4. They will tell each other that your face is black. ..... e.t.c
.
.
ALL THE BEST to all for this question.
given an ASCII string, return the longest substring with unique characters. Ex: dabcade => Ans: bcade.
class A {
public void method1();
public void method2();
public void method99();
public void method100();
}
Another factory class returning object of class A, how to implement logging mechanism, which should log entry and exit of each method call in class A.
Find the kth largest element in the union of two sorted arrays (with duplicates)
write a program to perform divison operation of two numbers without using /, %, and modules operatot
How many squares are in chess board?
Give an example for factory pattern (not abstract factory) with code
write a merge function to merge two BST's (both bst's having unique elements)
Given an integer array, convert it into a linked list with each node containing one sequence.
Please reply on manish.89july@gmail.com
Given an integer array with sequence of numbers, come up with a way to compress the data without losing the information. Based on the compressed data, it should be possible to construct the original integer array.
Please reply on manish.89july@gmail.com
Given an integer array, find the longest sequence and print it.
Please reply on manish.89july@gmail.com
Find the number of sequences in an integer array. A sequence is a list of numbers(more than one number) that comes in strict numerical order like [3, 4, 5, 6].
Please reply on manish.89july@gmail.com
Stream has 2 methods
char getNextChar()
bool hasNextChar()
Stream is expected to have 1 M characters. Your application cant store them.
Want to find the 1st unique character in the stream
You do not know anything about the technology you need to work on, you got a bug to solve, how would you start
Analyze these two pseudo code.
i.if(a<b)
if(a<c)
print("a smaller")
else
printf("c smaller")
else if(b<c)
print("b smaller")
else
print("c smaller")
ii.if(a<c)
if(a<b)
print("a smaller")
else
printf("b smaller")
else if(c<b)
print("c smaller")
else
print("b smaller")
Print a Random word from a file. Input is "path to a file",
constraints- No extra memory like hashing etc. All the words in the file should have equal probability.
How will you remove duplicate characters in a string
You are given an array which contains coin denominations. e.g. d = {1,2,3,5,8,12,15,21,37,56}. Each of these denominations are in infinite numbers. Write a program to produce the minimum number of coins(with denomination) which sum up to a given value. e.g. 189
output: 3(56)+1(23) = 4
you may produce output as 56->56->56->23
You are given 2 fair dices, whose all 6 faces are blank. You have to fill these faces with 0-9(you can repeat some digits, as there are 12 faces) such that, you should be able to produce all the dates of an English month.
e.g. you should be able to show 01 02 ....09 10.....30 31
Given two binary trees. Write a function to determine whether they are similar or not.
Given a string (an array of characters). Find the longest sub-string with less than 3 repeatable characters. Example: for string "abbc", "abb" is the sub-string.
Can you do it with O(n) on the time constrain?
Given a word and special characters print all the combinations of that word along with atmost 2 special characters
Word - test
special characters 0-9,%,#,&,!
Eg: test, test1, test2, te3st, te1!st, test#%, 12test, !te5st, t0est&, etc. etc.
Given 2 eggs and a building of 100 floors, devise a strategy to find the floor from which an egg would break such that the from the immediately lower floor the egg would not break
Given two arrays of integers, unsorted. Write a program to find the common elements within the two.
how to read a character from console(output screen) in turboc in c++
Given List of some servers, if a server has some problem and if we want to load balance the servers how would you perform add, delete or pick a server at random most efficiently.
Given a board of snakes and ladders game, provide an algorithm to find the minimum number of dice rolls required to reach 100 from 1.
Test cases for finger print reader say in a laptop to login. Here you can swipe your finger to have a secured login. e.g. I will swipe my finger and the system will allow me to login.
Given a 2-D MxN matrix having each value as difficulty for the block. A frog is starting from a point Matrix[0][0] and will have to reach Matrix[M-1][N-1]. It can jump any step in one go [ 1, 2, ..... M-1] horizontally OR [ 1,2,3,.... N-1] vertically
Each difficulty value is positive. Write code to give path trace for frog.
Two structure to use -
struct node
{
int x;
int y;
struct node *next;
};
struct path
{
int difficulty;
struct node *pathlink;
}
Ex matrix - 4X4 matrix
7 9 2 11
13 23 1 3
14 11 20 6
22 44 3 15
Minimum difficulty = 7 (a[0][0])+ 2(a[0][2]) +3(a[3][2])+15(a[3][3]) = 27
Path trace will have = 7->2->3->15
You have a list of 1 million distinct English words. Each word is between 1 to 40 letters long and contains only alphabets, no space or special characters. The list is already sorted alphabetically.
Given a word shorter than 40 letters, find all words in this list that are only 1 letter different from this word, spelling order is not important.
There are 3 types of matches: 1. Swap one letter with another and you have an exact match 2. Remove one letter and you have an exact match and 3 Add one letter and you'll have an exact match. For example: Given the word "coverage", these are valid matches:
1. "converge". Swap 'n' with 'a'
2. "coverages". Remove 's'.
3. "overage". Add a 'c'.
What's the time complexity of your algorithm?
Can your algorithm handle the request to find words that are 2 letters different from the given word?
Given an integer (assume it's smaller than 50), write an algorithm that will generate all possible combinations of integers greater than 1 and they produce a sum equals to this number. The same number can appear more than once in a combination. What's the time complexity of your algorithm?
For example:
<=1 -> {}
2 -> {2},
3->{3},
4->{[4], [2, 2]},
5->{[5], [3, 2]},
6->{[6], [4, 2], [3, 3], [2, 2, 2]}
7->{[7], [5, 2], [4, 3], [3, 2, 2]}
8->{[8], [6, 2], [5, 3], [4, 4], [4, 2, 2], [3, 3, 2], [2, 2, 2, 2]}
....
I have 10 million 10-bit integers to sort, how would you sort them and what's the time complexity?
Follow-on question: Instead of sorting integers, I now have 10 million pairs to sort. Each pair consists of a 10-bit integer and an object, the sort order is determined by the 10-bit integer. Will your original sort algorithm hold or do you need sort it differently?
(A word of advice: Ask as many questions as you want during the interview, but you MUST be quick. Also, don't mention anything until you've thought it through clearly, otherwise you're just inviting more questions. Time is of essence, you're too slow if this question takes you more than 15 minutes to come up with the optimal solution, because remember, you have to leave time for explanations and other questions)
Hi All, Recently I came across an interesting problem. Following is the problem description. I would like to have your thoughts on the problem.
Implement linux "tail -n" command in java:
Restrictions:
1) Should read file only from top to bottom.
2) File size can range from 1KB to 1TB.
3) System has only 32MB of RAM.
Given an integer array, sort the integer array such that the concatenated integer of the result array is max. e.g. [4, 94, 9, 14, 1] will be sorted to [9,94,4,14,1] where the result integer is 9944141
Can we solve this in less than n square time?
n square algo is here
private bool isSwapNeeded(int i, int j)
{
int isum = i * (int)Math.Pow(10, NumberOfDigits(j)) + j;
int jsum = j * (int)Math.Pow(10, NumberOfDigits(i)) + i;
return isum > jsum;
}
private int NumberOfDigits(int i)
{
int noOfDigits = 0;
if (i == 0)
return 1;
while (i>0)
{
noOfDigits++;
i /= 10;
}
return noOfDigits;
}
public int[] MaximumConcatArray(int[] input)
{
int j;
for (int i = 1; i < input.Length; i++)
{
j = i;
while (j>=1 && isSwapNeeded(input[j],input[j-1]))
{
input[j] = input[j] ^ input[j - 1];
input[j-1] = input[j] ^ input[j - 1];
input[j] = input[j] ^ input[j - 1];
j--;
}
}
return input;
}
write the test cases for the Swiping Pad ....??
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <stdint.h>
#define _uint64_t
unsigned long long int i,R,L;
int f1(unsigned long long int num);
//unsigned long long int a[999999999];
unsigned long long int *a=NULL;
unsigned long long int j,r;
unsigned long long int main()
{
//printf("enter Minimum value for Delicious Dishes\n");
scanf("%llu",&L);
//printf("enter Maximum value for Delicious Dishes\n");
scanf("%llu",&R);
j=L+1;
a=(unsigned long long int *)malloc(sizeof(R-L));
//int f1(int a[]);
for(i=0;i<(R-L);i++)
{
//j=L+1;
*(a+i)=j;
j=j+1;
}
//printf("Now Delicious Dishes List is Ready.....:\n\n { ");
for(i=0;i<R-L;i++)
{
r=f1(*(a+i));
if(r==1)
{
//printf("not Delicious Dishes List:\n");
//printf("%d",a[i]);
}
else{
printf(" %llu ,",*(a+i));
}
}
//printf(" };\n\n");
//int random;
//srand(time(NULL));
//random=a[rand()%(sizeof(a) /sizeof(a[0]))];
printf("%llu\n ",*(a+4));
return 0;
}
int f1(unsigned long long int k)
{
unsigned long long int rep=0;
while(k>0)
{
if(rep & 1 <<(k%10))
return 1;
rep|= 1 << (k % 10);
k = k / 10;
}
return 0;
}
its give result correct but in large input value ex L=123456,R=123456789 its give core dump i have already using standard gcc compiler and take unsigned long long int but still giving runtime error core dump can anyone hel me for resolve this bugs
Problem Statement :
• Given an 4n X 4n Matrix, where n is a positive integer taken as input. Imagine the matrix consisting of two interleaved coils whose centers are at the centre of the matrix. Implement a java program which takes an integer (n) as input and prints the two coils in two seperate lines.
Please have a look at the below examples to get a sense of what the two coils are :
• Example 1:
• Input: 1
• Matrix:
01 02 03 04
05 06 07 08
09 10 11 12
13 14 15 16
• Output the Two Coils as:
- Coil1: 10 06 02 03 04 08 12 16
- Coil2: 07 11 15 14 13 09 05 01
• Example 2:
• Input: 2
• Matrix:
01 02 03 04 05 06 07 08
09 10 11 12 13 14 15 16
17 18 19 20 21 22 23 24
25 26 27 28 29 30 31 32
33 34 35 36 37 38 39 40
41 42 43 44 45 46 47 48
49 50 51 52 53 54 55 56
57 58 59 60 61 62 63 64
• Output the Two Coils as:
- Coil1: 36 28 20 21 22 30 38 46 54 63 52 51 50 42 34 26 18 10 02 03 04 05 06 07 08 16 24 32 40 48 56 64
- Coil2: 29 37 45 44 43 35 27 19 11 12 13 14 15 23 31 39 47 55 63 62 61 60 59 58 57 49 41 33 25 17 09 01
You are given two database instances at different geographical locations, which are updated too frequently. Different requests are performing different operations on the two instances.
How will you keep these in sync.
Given an array of integers and a function Arrange(int position), the function takes the position of an element in the array as input and puts this element at the last position and arranges the array. Now the objective is to sort the array using the Arrange function minimum number of times.
/* program for construction of full binary tree */
#include <stdio.h>
#include <stdlib.h>
/* A binary tree node has data, pointer to left child
and a pointer to right child */
struct node
{
int data;
struct node *left;
struct node *right;
};
// A utility function to create a node
struct node* newNode (int data)
{
struct node* temp = (struct node *) malloc( sizeof(struct node) );
temp->data = data;
temp->left = temp->right = NULL;
return temp;
}
// A recursive function to construct Full from pre[] and post[].
// preIndex is used to keep track of index in pre[].
// l is low index and h is high index for the current subarray in post[]
struct node* constructTreeUtil (int pre[], int post[], int* preIndex,
int l, int h, int size)
{
// Base case
printf("preindex : %d %d %d\n", *preIndex, l, h);
if (*preIndex >= size || l > h)
return NULL;
// The first node in preorder traversal is root. So take the node at
// preIndex from preorder and make it root, and increment preIndex
struct node* root = newNode ( pre[*preIndex] );
++*preIndex;
// If the current subarry has only one element, no need to recur
if (l == h)
return root;
// Search the next element of pre[] in post[]
int i;
for (i = l; i <= h; ++i)
if (pre[*preIndex] == post[i])
break;
// Use the index of element found in postorder to divide postorder array in
// two parts. Left subtree and right subtree
if (i <= h)
{
root->left = constructTreeUtil (pre, post, preIndex, l, i, size);
root->right = constructTreeUtil (pre, post, preIndex, i + 1, h, size);
}
return root;
}
// The main function to construct Full Binary Tree from given preorder and
// postorder traversals. This function mainly uses constructTreeUtil()
struct node *constructTree (int pre[], int post[], int size)
{
int preIndex = 0;
return constructTreeUtil (pre, post, &preIndex, 0, size - 1, size);
}
// A utility function to print inorder traversal of a Binary Tree
void printInorder (struct node* node)
{
if (node == NULL)
return;
printInorder(node->left);
printf("%d ", node->data);
printInorder(node->right);
}
// Driver program to test above functions
int main ()
{
int pre[] = {1, 2, 4, 8, 9, 5, 3, 6, 7};
int post[] = {8, 9, 4, 5, 2, 6, 7, 3, 1};
int size = sizeof( pre ) / sizeof( pre[0] );
struct node *root = constructTree(pre, post, size);
printf("Inorder traversal of the constructed tree: \n");
printInorder(root);
return 0;
}
why does constructTreeUtil function needs to pass preindex as a pointer to integer?
why not simply integer
In a file stream, you are at unknown position. You have an API to move forward or backward 1 Byte at a time and the pointer points to first bite.
Assumption: Chinese character occupies 4 bytes and English character occupies 2 bytes. Chinese character always starts with first bite value 1 (means first bite of the character out of 4 bytes) and English character with first bite value 0. Any character (Chinese or English) is identified by first bite of fist Byte of the character.
Example: x is 0 or 1
Chinese 1xxxxxxxx|xxxxxxxxx|xxxxxxxxx|xxxxxxxxx
English 0xxxxxxxx|xxxxxxxxx
Problem Statement: You need to develop an algorithm or code (C++) to find out the character that the current pointer pointing to.
Suppose we have a some part of stream like CCECC and pointer at 6th Byte, then the current pointer that it is pointing to Chinese character.
C | C |E | C | C
BBBB|BBBB|BB|BBBB|BBBB
++++ ++
You have a large number of data maybe millions. Which is the best data structure to use?
Following operation needs to be performed :
Insert, Delete and Searching.
You have a matrix of size (m x n). find submatrix of size (k x k) with maximum possible sum. 0<k<m and 0 <k <n
[HINT] use DP
Given unsorted array (contains -ve numbers also), write a method to return max sum. Condition is two numbers should not adjacent to each other.
write a insert method for singly linked list, so that it will insert elements in the ascending order.
Given n length path (assume array with 0's and 1's), each step either a rock or acid bucket (0 is acid and 1 is rock), need to find the jumping pattern of the from to cross the given path. Conditions are:
lets consider, curretly frog jumping at speed s, at each step
it can maintain same speed (s)
or increase by one step (s=s+1) or
decrease by one step (s=s-1);
find the jumping sequence for the given input.
1. Consider you have a function named
int find(sortedArr,val)which return the index of value val in the sorted array in O(1).
Constraint: You must have a sorted Array for that.
2.You know that you have a new array which was sorted but its elements have been moved by some Pivot which currently isn't known.
The mission:
Write a function which use find(sortedArr,val) in this new array to find the index of a given value in O(1) also.
Thank you
Write positive test cases to test this function
bool FileCopy(string source, string destination)
You are given a binary search tree T of finite (means can fit in memory) size n in which each node N contains
- integer data element
- pointer to left child
- pointer to right child
- pointer to in order successor (which is set null for each node)
Set all in order successor pointers of the given binary search tree.
Given a conteneous input stream of integer.. Find out Maximum N number at any given instance..
You are given with N number of linklist of max size k. Some linklists are merged with each other and some are stand alone. Return all stand alone linkedlist... not just number of stand aone...
Given an 2D array which is row wise sorted and column wise sorted. Search a given element fron the array.
Search results shows short segments ("snippets") of results and highlights query terms.
Look, for example, at a search for [buy apple ipad] in [tablet]:
http://www.search.google.com/search?find_desc=buy+apple+ipad&find_categ=tablet.
Only a part relevant to query is shown which is shorter than the entire result.
For this question you will write a function that finds the most relevant snippet for a document and highlights all the query terms that appear in the snippet (like the highlights you saw on the linked search page). It is up to you to define what constitutes a good snippet and how big the snippets will be.
Indicate highlights by surrounding the text to be highlighted with [[HIGHLIGHT]] ...
[[ENDHIGHLIGHT]].
Suppose there is an array with numbers :
1, 14, 5, k, 4, 2, 54, k, 87, 98, 3, 1, 32
Output for this can be assuming k =20
1,14,5,4,2,3,1,k,k,54,87,98,32
Now sort this array in a way all k are in middle and all values on left of k are smaller (in any order) and on right are larger (in any order)
Note: k is an integer value within range of 1 - 32768
Follow up: Sorting is ok. what sorting you want to use ? still is sorting necessary ? are there any other approaches ?
Follow up: Used External array with 2 pointers and 3 pointers approach. They wanted more efficient solution.
How would you design an Excel sheet's Data structure. You need to perform operations like addition. The excel sheet is very sparse and is used to store numbers in the range 1-65K. Index for a cell is known.
How to sort a 1000 GB file with ram size is 4 GB only. Which algorithm or data structure we need to use to sort these files?
Follow Up: External sort is Ok... but how can you make this solution more efficient...
Follow Up 2: Ideal chunk size for external sort (I said 512 MB based on my experience with MS Word 2013, it can not load file size >512 MB)
Design a system for showing quotes on the web.
For example, when the user is looking at page A, part of which is reproduced in page B, the system could highlight part of page A present the user with a link to page B.
This is an open-ended system design question.
What constitutes a quote?
How do you find quotes?
How do you make it scale to the web?
How do you handle updates?
How would you arrange the servers?
What data structures would you use?
How much storage would you need?
How would the user agent present information about quotes?
Implement second/minute/hour/day counters Feb. 4, 2011 8:59pm
Implement the API that counts the number of events in the last sec/min/hr/day:
SMHDCounter {
void Increment();
int LastSecCount(); // also functions for minute, hour
int LastDayCount();
}
Additional requirements
- you require that the data be quite fresh
- how much storage will they take up
- make sure this works for an active counter, getting 100s of events a second.
- keep the implementation fast. E.g. under 10 mS. Or even better motivate by saying we might have 50 of these SMHD counters on a single status page, and ask the candidate how fast their solution should be.
Matrix of size MxN filled with characters is given. Assume that we have a dictionary of words and searching whether a word present can be done efficiently. Find all dictionary words. A word can traverse in any direction, but the position should not be repeated for a particular word.
Ex: A word can occupy (1,1),(2,1),(2,2) positions in matrix.
Words can overlap(Ex1: understand--> under, stand , Ex2: mismatch,mistake,match,take)
File-1 is having 5 million strings and File-2 is having 1 million strings. Give an Algo to remove duplicates and merge these files (Need not be sorted) into File-3.
find ginen BT is BST or not?
An array of n length, filled with 0's,1's and 2's, how to sort effectively?
Input:{0,1,2,2,1,1,0,2,1,0}
Output: {0,0,0,1,1,1,1,2,2,2}
Given two arrays, A and B, both containing integers, find values that appear in both arrays and output them.
I knew the fastest answer to this, which is basically adding array A to a hashmap and then checking if that map contains each element of B, which is an O(n) operation, but uses memory in O(n) as well. The interviewer then asked if I could figure a way of doing this with a complexity of O(n) without using any extra memory, basically just O(1) for memory.
Is this possible? I could not think of a simple quick solution for this on the fly, but I imagine it is possible.
Here is the code I wrote during the interview.
import java.util.*;
public class ArrayFun {
public static void main(String[] args) {
int[] a = {1,2,3,4};
int[] b = {2,5,6,7,3,2};
ArrayList<Integer> matches = ArrayFun.findMatches(a,b);
for (int i = 0;i<matches.size();++i) {
System.out.println(matches.get(i));
}
}
public static ArrayList<Integer> findMatches(int[] a, int[] b) {
HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
ArrayList<Integer> matches = new ArrayList<Integer>();
for (int i = 0;i<a.length;++i) {
map.put(a[i],0);
}
for (int i = 0;i<b.length;++i) {
if (map.get(b[i]) != null && map.get(b[i]) == 0) {
map.put(b[i],1);
matches.add(b[i]);
}
}
return matches;
}
}Also, another quick question, is it typical for a phone interviewer to only ask you one question? I think it would be kind of difficult to ask more than one technical question, including coding, in such a short amount of time, i.e. < 1 hour
Dictionary d: boolean isWord(String)
Input: "thisisawesome"
Output:
this is awesome
this is awe some
isWord("this") == true
isWord("esome") == false
How to write an XOR cipher program using the C programming language.
Program must accept as input from the user a value between 0 and 255 to be used as the secret key, the name of the input file and the name of the output file. No line in the input file should contain more than 4096 characters.
After the user would have provided their secret key, your program should read and perform an XOR cipher on the contents of the input file and write the result to the output file.
If the input file has already been encrypted and the identical secret key that was used to perform the initial encryption is provided, then the contents of the output file should be deciphered into its original plain text.
Show:
1, Algorithm and flow chart
2, Source code.
Anyone with a clue to this task?
Implement a circular queue of integers of user-specified size using a simple array. Provide routines to initialize(), enqueue() and dequeue() the queue. Make it thread safe.
Design an algorithm to find the least common ancestor of two nodes in a Binary tree(Note: Its not a binary search Tree)
Node Structure is given as
Class Node{
int data;
Node leftchild;
Node Rightchild;
}Given a big string (str1) find (s1) and replace by (s2).
Example :
str = "Hi i am abc and i am in abc"
s1 = "abc"
s2 = "pqrstuv"
So final o/p :
str1 = "Hi i am pqrstuv in pqrstuv"
Develop recursive program.
F(1) = 1.
F(2n) = F (n) and F(2n+1) = F(n) + F(n+1).
: Implement atoi function. Define your own function signature in the language of your choice. Once done, write a few test cases
how to write test cases
design software system for super market
how to sort a 2D array? constraint- algo should be as small as possible.
consider a B2C website like Amazon, which will receive thousands requests from buyer per minutes. How will you design the "shop cart " component for it? where should the customs' shop cart data stored?
generic HashMap implementation
Design a scalable server for the hangman game
How do you search thrgough huge flat file?
Given a source string and a destination string write a program to display sequence of strings to travel from source to destination. Rules for traversing:
1. You can only change one character at a time
2. Any resulting word has to be a valid word from dictionary
Example: Given source word CAT and destination word DOG , one of the valid sequence would be
CAT -> COT -> DOT -> DOG
Another valid sequence can be
CAT -> COT - > COG -> DOG
One character can change at one time and every resulting word has be a valid word from dictionary
Define a structure / class to hold a very big number (way bigger than bigint) and add a member functions to increment the number by 1 and decrement the number by 1
The programming problem is:
Each turn of a simulation, car A has a 10% chance of moving 5 feet forward, and a 90% chance of staying still. Similarly, each turn of the simulation car B has a 60% chance of moving 1 feet forward, and a 40% chance of staying still. A race consists of however many turns in the simulation it takes to travel 100ft. Write a simulation to run such a race, and run it 100 times. Count how many times car A wins and how many times car B wins. Do the results match up with what you would expect from a mathematical analysis of the problem?
Given a list of objects or strings with the index information, the list has some gaps inside.
Implement a function to take a starting number and the total number, return the new list to contain all the items not in the given list.
eg. Given list1: {item1, item2, item3, item5, item6, item8, item9}, starting number is 3, total number is 10, then return the list2: {item4, item7, item10, item11, item12, item13, item14, item15, item16, item17}
Given a string, you have remove duplicates from it in O(n) time and O(1) space.
Please tell basics difference between windows system programming and Unix system Programming.
we have streaming numbers, where numbers may repeat for example 1,2,5,11,2,8,2,9 number 2 is repeating. provide nth number where n is the index of number, excluding the repeated number. hence for above example if n is 3 return 8 because 2 is repeating so excluded. best time and space. code in java.
program to give 5 numbers, omit last number then first 4 numbers should be multiplied by 2 and add then divide by 4 and the number must be similar to omitted number
program to get n number of input and change it as 2 power n+1 and find whether the number is prime or not
program to get a list of arrays like 121 121 121 and eliminate duplicate and print 121 as output
program to print only alphabets by getting input as j@1vu etc
A Matrix of cells is given. A cell may be desert (represented as 1) or forest (represented as 0). Now every year all forests adjacent to desert convert to deserts. You are supposed to find out how many forests will be there after 'k' years (also give their location).
** : on phone interview, interviewer will ask you to code on the online real-time editors like collabedit.com, sync.in or docs.google.com
How to find maximum path sum in a binary tree.
The path need not be a top-bottom, can start and end nodes need not be root or leaf, path can start in left/right subtree and end in right/left subtree wrt any node.
Give a BST and a number. we need to find next bigger number in BST.
We have n number of sorted array for fixed length.
Now we have to merge these and need to save finaly result array into given array.
Note- we can't use extra space except the given array.
Here is the second:
def babylon(a):
def test(x):
return 0.5 * ((a / x) + x)
return test
def sqrt(a):
return fixedPoint(babylon, 0.0001)
This code has a bug in it. You can fix this by correcting exactly one line of the definition.
Successive approximation is a general method in which on each iteration of an algorithm, we find a closer estimate of the answer for which we are seeking. One class of successive approximation algorithms uses the idea of a fixed point. If f(x) is a mathematical function, then finding the x such that f(x) = x gives us the fixed point of f.
One way to find a fixed point is to start with some guess (e.g. guess = 1.0) and, if this is not good enough, use as a next guess the value of f(guess). We can keep repeating this process until we get a guess that is within epsilon of f(guess).
Here is a slightly incorrect definition of this function:
def fixedPoint(f, epsilon):
"""
f: a function of one argument that returns a float
epsilon: a small float
returns the best guess when that guess is less than epsilon
away from f(guess) or after 100 trials, whichever comes first.
"""
guess = 1.0
for i in range(100):
if f(guess) - guess < epsilon:
return guess
else:
guess = f(guess)
return guess
This function definition has a bug in it. You can fix this by correcting exactly one line of the definition.
Assuming you have corrected the implementation of the fixedPoint function, we can use it to compute other useful things such as square roots. In particular, the square root of a number, a, is the fixed point of the function f(x)=12(a/x+x).
The next two questions define two different implementations of this idea. Each has one incorrect line of code. The first is below:
def sqrt(a):
def tryit(x):
return 0.5 * (a/x + x)
return fixedPoint(tryit(a), 0.0001)
This code has a bug in it. You can fix this by correcting exactly one line of the definition.
Design a O(n) algo for following scenario: Given a n-element array, n being even, find atleast (n/2) distinct element pairs that when summed is divisible by an integer k. eg: (a,b);(b,a) not allowed & (a+b)%k==0
Determining trending topics
How do you think Twitter determines trending topics?
If needed, explain that trending topics are N most common occurring substrings across all tweets in a given time window, which is constantly moving. Later you can expand the question by putting the scale constraint considering the rate at which tweets come in, etc.
first non repeating character from a given string
find the sub array of sum K from the the given unsorted array
only pre oder of BST is given need to construct BST in O(n)...O(nlog(n)) is rejected
matrix contains a 1's and 0's find the entities filled with 1's and bounded by 0's ...we need to give the no of such entities exists in the matrix
given a binary search tree, find the any 3 nodes such that sum is K
find the largest BST from the given Binary tree
3)array contains only 0 and 1's need to sort the array such that all zeros at first and 1's later part of the array
2)2D graph, there are two pints (x1, y1) (x2, y2) x1<x2 & y1<y2 and we are supposed to move in positive direction either right or up i.e (x1+1) or (y1+1) only
we need to find the no of paths to reach that point x2, y2
total 3 questions
1)pre fix to post fix
What is shallow copy?
What is multithreading
Difference between process and thread
Class A, B and C all cout their own names in their constructor. C is B’s subclass while it has an instance of A as its private member. When a C object is instantiated, what will the order of printed letters?
C++ class animal has virtual method render which prints “Animal” while its subclass Tiger has virtual method render which prints “Tiger”. Tiger kitty;; Animal * beast = &kitty; what is the outcome of beast->render()?
Given a number x = 0x25. Convert it into y = 0x25252525.
If a key has to be inserted in binary tree, say the value of root as well as the key to be inserted as same. Will the key becomes left child or right child of Root? Can binary tree have duplicate values? If yes, why, If no why?
int num=1;
*(char*)#
//what this statement does basically
because when it is 1 it means lower order byte is 1 else higher order byte is 1(used for calculating little endian and big endian).
McDonald’s sells Chicken McNuggets in packages of 6, 9 or 20 McNuggets. Thus, it is possible, for example, to buy exactly 15 McNuggets (with one package of 6 and a second package of 9), but it is not possible to buy exactly 16 McNuggets, since no non- negative integer combination of 6's, 9's and 20's add up to 16. To determine if it is possible to buy exactly n McNuggets, one has to find non-negative integer values of a, b, and c such that
6a+9b+20c=n
Write a function, called McNuggets that takes one argument, n, and returns True if it is possible to buy a combination of 6, 9 and 20 pack units such that the total number of McNuggets equals n, and otherwise returns False. Hint: use a guess and check approach.
Write a recursive procedure, called laceStringsRecur(s1, s2), which also laces together two strings. Your procedure should not use any explicit loop mechanism, such as a for or while loop. We have provided a template of the code; your job is to insert a single line of code in each of the indicated places.
def laceStringsRecur(s1, s2):
"""
s1 and s2 are strings.
Returns a new str with elements of s1 and s2 interlaced,
beginning with s1. If strings are not of same length,
then the extra elements should appear at the end.
"""
def helpLaceStrings(s1, s2, out):
if s1 == '':
#PLACE A LINE OF CODE HERE
if s2 == '':
#PLACE A LINE OF CODE HERE
else:
#PLACE A LINE OF CODE HERE
return helpLaceStrings(s1, s2, '')* 54. An array of integers of size n. Generate a random permutation of the array, given a function
rand_n() that returns an integer between 1 and n, both inclusive, with equal probability. What is the
expected time of your algorithm?
A huge room is spanned by square tiles. Given the dimensions ( MXN ) of the room, determine how many tiles does any one of the diagonal pass through.
We say that the diagonal passes through a tile if it divides the tile into 2 non-zero areas.
INPUT
The input consists of several test cases. The first line of the INPUT is an integer T denoting the number of testcases. For every test case, there's a single line containing two positive integers M,N.
OUTPUT
For every test case, output a positive number denoting the number of tiles the diagonal passes through.
SAMPLE INPUT
2
4 4
5 6
SAMPLE OUTPUT
4
10
Given a 2D Boolean matrix consisting of 0s and 1s. Find the largest size rectangle having all four borders as 1. The interior of it may or may not be entirely filled with 1s.
what is x86 and x64 why it is require is there any possibility that it will move forward like x 128
A tuple can contain a list as an element.
True
or
False
All O(1) functions take exactly the same amount of time to run.
True
or
False
After a mutable object has been created, its identity can change.
True
or
False
After a mutable object has been created, its value can change.
True
or
False
Given two node values for a tree, find LCA. Consider edge cases - (1) If there exists only one value in the tree, return null. (2) If none of the values exist in the tree, return null. (2) Handle ancestors for duplicate values like -
20
/ \
10 50
/ \ / \
10 17 40 60
/ \
5 15
So for above tree if values 5 and 17 are given, there LCA is the upper 10 and not the lower. You can exemplify something I bet :-)
Given a sorted array of size n implemented as ring buffer, so that when array has reached (n-1) index, it will be overwritten from 0th index and likewise it will continue. Given any number, find its index in the array in less than linear time. Interviewer asked to consider the edge cases which I could not quite understand during the interview. I told, the edge cases would be no-element array, array with one element and such.
I will try to state the question. We all know mobile phone's keypad where "2" is mapped to ABC, "3" to DEF and so on. Given any sequence of integers, find all the (matching) combinations in your phone book.
You are given an input form such as the following
(1, (2, 3), (4, (5, 6), 7))
Each element is either a number or a list (whose elements may also be numbers or other lists).
Output the numbers as they appear, stripped down into a single list.
E.G. (1, 2, 3, 4, 5, 6, 7)
(Complication - how does your code handle the case of ((((5)))) vs just ( 5 ) ? )
You are given a string that is in roman numeral format.
Output the integer representation.
E.G. You're given XIV
Output 14.
Given a web site log file, find the most visited URL. Also find the top ten most visited URLs.
Write an algorithm to print out how many extra duplicates there are in a binary search tree.
input 1:
2
/ \
1 2
output 1:
2 1
input 2:
3
/ \
2 3
/ \ \
1 2 4
/ \
3 4
\
5
\
5
output 2:
2 1
3 2
4 1
5 1
Given:
Node {
int value;
Node left;
Node right;
}
What would be an example of glass-box testing?
(ruby on rails)
Throwing random data at your application to see if it breaks
Testing a particular code path in the program
Automatically making small but syntactically legal changes to the program
Testing the result of a predetermined input to the program
What is the benefit of using factories over fixtures?
(ruby on rails)
Factories create full-featured objects, but fixtures do not
Factory objects persist across specs, while fixture objects do not
Factories keep tests independent, while fixtures may not
All objects from a certain factory are exactly the same, while objects from a fixture may vary
What is the main difference between BDD and TDD?
(ruby on rails)
BDD focuses on validation while TDD focuses on verification
BDD focuses on verification while TDD focuses on validation
BDD is better than TDD at testing methods independently
BDD generally uses mocks and stubs more than TDD
Which of the following statements are true regarding mocks in RSpec? Select all that apply.(ruby on rails)
Mocks are used to isolate tests from the database
Model mocks automatically have access to all existing methods of the model
Mocks can be created with default attribute values
Which of the following lists the kinds of tests in order of increasing code exercise complexity?(ruby on rails)
Integration tests, functional or module tests, unit tests
Unit tests, integration tests, functional or module tests
Unit tests, functional or module tests, integration tests
Functional or module tests, unit tests, integration tests
Your test randomly changes the comparison operators in your conditionals. This is which kind of testing?
Mutation test
Glass-box test
Black-box test
Fuzz test
Which of the following guarantees that you have exhaustively unit-tested a piece of code?
100% C0 (statement) coverage
100% C1 (branch) coverage
100% C2 (path) coverage
None of the above
For a service like TMDb with an HTTP-based RESTful API, a Ruby wrapper library such as the ruby-tmdb gem is necessary in order to call the service from a Ruby app.
True
False
RSpec's stub method can be used to override a method call on
an instance only
a class only
an instance or a class only
any Ruby object
Sally wants to create a dating website and decides to write an algorithm that takes a list of male and female users' preferences and returns the best matching of males with females. To test her algorithm, she manually calculates the best match. She then runs the algorithm and checks to see if the observed output matches with her manual calculation. What FIRST principle is clearly not being followed?
Fast
Independent
Repeatable
Self-checking
Timely
High coverage can always be achieved by writing a unit test for every method.
True
False
Write code using commands below for two rovers to meet. Two rovers are dropped on Mars. Imagine Mars to be a straight infinite plane. When the rovers are dropped on Mars they are dropped with parachute. So their initial position on Mars is on parachute.
Only commands possible to execute:
1. Go left
2. go right
3. NO OPERATION
3. If on parachute go to lablel.
Label can be a piece of code with a name where we can transfer execution
Using ONLY commands above write code for rovers to meet.
int match(string input, string pattern)
input= input string
pattern = pattern that we are looking for in a string.
The pattern can contain * wild char which atleast matches 1 char, that is A*B doesnt match AB.
return = index of start of first such sequence .
How to implement stack using queue
How does JVM decides whether deadlock has happened or not?
What is the Data Structure/ Algorithm JVM uses to know for the deadlock condition?
Remove the duplicates in a linked list
I don remember the exact question. I guess it was " Given an array where the first and 2nd haalf of the array are sorted. Print the sorted array"
Online Test: Find the least common ancestor for any two given nodes in a Binary search tree
For a given integer X, consisting of not more than 6 digits, write the value of the largest palindrome smaller than X and the value of the smallest palindrome larger than X to output.
Given an array of n integers, Display the numbers with even frequency.
Reverse a string. Give complexity.
Implement a stack using two queues (no coding necessary)
Check if a tree is a binary search tree
From the set of natural integer numbers
Let x = 1234 = {1, 2, 3, 4}
Let y = 2410 = {2, 4, 1, 0}
Write an algorithm to compute the rearrangement of x that is closest to y but still greater than y. Both x and y have the same number of digits.
So in the example above, the answer would be { 2, 4, 1, 3 } = 2413 which is greater than y = 2410 and closer than any other arrangements of x.
And whats the time complexity of this algorithm?
implement Java's pow function, then list test cases, examine performance, see if you can optimize performance.
public double pow(double a, int b)
(screening round)
Implement atoi. What would be your approach converting for string to hex.
(screening round)
Given two sorted arrays, merge them into result array with sorting. Time and Space Complexity.
Generate all binary trees of n nodes.
Is there any such algorithm for Search procdure whose time complexity get decreases as the size of database increases?
Given a ternary string, you have to count the total number of contiguous substrings (contigious set of characters), that you can form from this given string such that they comprise of either only one or two different characters.
Please note that a unique substring will be decided by its starting and ending indices. So, a substring 'ab' with starting and ending indices being 1 and 2 respectively should be considered different from a substring 'ab' with starting or ending indices (or both) other than 1 and 2 respectively.
For example:
input ternary string - aabc
output - 8
The above string comprises of the following substrings that have either one or two of the characters - a, a, b, c, aa, ab, bc and aab. So the final answer is a total of eight substrings.
input ternary string - abc
output - 5
The above string comprises of the following substrings that have either one or two of the characters - a, b, c, ab and bc. So the final answer is a total of five substrings.
input ternary string - baaccb
output - 16
The above string comprises of the following substrings that have either one or two of the characters - b, a, a, c, c, b, aa, cc, ba, ac, cb, baa, aac, acc, ccb and aacc. So the final answer is a total of sixteen substrings
Consider there are n matrices. For eg, A, B, C and D are four matrices. Find the groupings of matrices during their product, the operations involved in your choice of grouping is minimal.
For eg, you can group like (AB)CD or (ABC)D or A(BC)D or A(BCD) .... But among these options in which grouping the operations of matrix multiplication will be minimal. Remember in matrix multiplication , multiplication and sum of elements are involved.
Given a string s, its roughness is calculated as follows: Let c1 be the letter that appears most frequently in s, and let c2 be the
letter that appears least frequently (c2 must appear at least once). The roughness of s is the number of occurrences of c1
minus the number of occurrences of c2. Write a program to find the minimum possible roughness of a string that can be
achieved if you are allowed to remove up to n characters in a string. Note: you are allowed to modify s by erasing between 0
and n characters, inclusive.
Input
First line of the input will be the string, s followed by a number (n) in next line indicating the maximum number of
modifications allowed
Output
Return the minimum possible roughness that can be achieved by such a modification
Given a matrix of 0's and 1's find the number of groups of 1's in the matrix.
A group of 1's can be formed if a 1 is present either vertically or horizontally to the adjacent 1 and not diagonally.
1 0 0 0
1 1 0 0
0 0 1 1
0 0 1 1
The above matrix has two groups of 1's while the one shown here has only one group
1 1 0 0
1 1 1 0
1 1 0 0
No restrictions on space complexity was given but the interviewer did mention that the time complexity should be efficient and that it should work for extremely large matrix's as well.
String getSentence(String text, Set<String> dictionary);
// text is a string without spaces, you need to insert spaces into text, so each word seperated by the space in the resulting string exists in the dictionary, return the resulting string
// running time has to be at least as good as O(n)
// getSentence("iamastudentfromwaterloo", {"from, "waterloo", "hi", "am", "yes", "i", "a", "student"}) -> "i am a student from waterloo"
Can the sizeof operator be used to tell the size of an array passed to a function?
Given an array, find all maximal sub-arrays in which all pairs have their sum greater than k. DP would give us a O(n^2) algorithm. Can we do better.
suppose k = 4
-4 9 10 4 -3 8 9 -2
Answer is:
-4 9 10
9 10 4
-3 8 9
8 9 -2
For an array of n integers and a number k between 2 and n, give an algorithm to determine if there are k elements that sum to zero. What are the time and space complexity?
For a given array size is know but elements using index is not accessible. 2 given functions are below:
1. getIndexOfNthLargest(int n) // returns the index of nth largest number. Like for n=1 the index of largest element will be returned, for n=2 the index of 2nd largest number will be returned.
2. reverseArray(int i) // reverse the elements of the array from index 0 to i
How to sort the array in place?
2 classes are given. class A and class B.
class A is having the object of class B and class A's method is calling class B's method. how would you write junit test for class A's method ?
I said that declare class B's object and call B's method but he said in that case class B's method can do something because of which test can fail. You only have to test class A.
In a hall there are many peoples, where some people know each other, one one person who dont know anyone but all other people know him, So we have to find that person.
You have to use this method
boolean knows(personA, personB){}
It will return true if person knows each other other wise false.
Given an array of numbers (integers) find all pythogorean triplets (a^2 + b^2 = c^2). print a,b an c and the indexes.
Prefix Expression to Postfix Expression.
Given two positions in a 2-D matrix, say (x1, y1) and (x2, y2) where x2>=x1 and y2>=y1. Find the total number of distinct paths between (x1, y1) and (x2, y2). You can only move in right direction i.e. positive x direction (+1, 0) or in up direction i.e. positive y direction (0, +1) from any given position.
Example: If the given coordinates are (3,3) and (5,5), the number of distinct paths are 6 : one going through 3,5 ; one going through 5,3 and four going through 4,4.
Given an array containing sequence of bits (0 or 1), you have to sort this array in the ascending order i.e. all 0' in first part of array followed by all 1's. The constraints is that you can swap only the adjacent elements in the array. Find the minimum number of swaps required to sort the given input array.
Example: Given the array (0,0,1,0,1,0,1,1) the minimum number of swaps is 3.
Note: You just need to complete the function given below for this task. The function is given a binary string as input and returns the required answer.
Problem : Move the chess piece "KNIGHT" from any location on a
"3 x 3" Chess Board and make it go to the far right
hand bottom corner^. Chess Board in the problem is
not the usual Chess Board of 8 x 8.
KNIGHT starting position may be any position on board
Program should exit when knight moves to 3 x 3 corner.
Here is how my Chess board looks.
1 2 3
-------------------------
| | | |
1 | | | |
| | | |
-------------------------
| | | |
2 | | | |
| | | |
-------------------------
| | | |
3 | | | X | <<<<------- KNIGHT should reach
| | | | this square.
-------------------------
Remember: KNIGHT moves in specific way such as 2 steps in
one direction and 1 step left/right.
If the KNIGHT starts are position (2,2) then it cannot move further and
you have to throw exception with some error message.
We are not interested in any UI programming.
Run command: "java <some class> x y", where x is x-coordinate
and y is y-coordinate(starting position of Knight)
on the chess board. For this problem x & y could be
1(min) and 3(max) values and any value(2) in between.
Given the root of a tree and two other nodes n1, n2. Find the distance between n1 and n2
Given a sorted string s1 and an unsorted string s2. Sort s2 based on the sorting algorithm applied in s1.
Ex:
s1 = fghab
s2 = abfmgfghnaixcv
Output: ffgghaabmnixcv
Estimate the # of unique strings with limited memory
Given a large array of strings S = [s1, s2, ... sN], determine Uniq(S) = how many unique strings there are in S.
(b) How large can N be to solve on one machine using only memory?
(c*) What if N is too large to fully fit in memory?
Random number generator
There is an ideal random number generator, which given a positive integer M can generate any real number between 0 to M with equal probability.
Suppose we generate 2 numbers x and y via the generator by giving it 2 positive intergers A and B, what's the probability that x + y is less than C? where C is a positive integer.
Input Format
The first line of the input is an integer N, the number of test cases.
N lines follow. Each line contains 3 positive integers A, B and C.
All the integers are no larger than 10000.
Output Format
For each output, output a fraction that indicates the probability. The greatest common divisor of each pair of numerator and denominator should be 1.
Input
3
1 1 1
1 1 2
1 1 3
Output
1/2
1/1
1/1
In a hashmap, how to delete all the odd entries? i.e, if hash map contains key1, value1, key2, value2, key3, value3, ... we've to delete all the odd entries, that is to remove all the keys alone without deleting values
JAVA Question:
There is one class which extends Thread and it takes "Symbol (Clubs, Heart, Dice, Spade)" as a parameter in constructor.
We've four threads one each for each symbol. Now they want to print as given below:
Dice A
Hearts A
Spade A
Clubs A
Dice 2
Hearts 2
Spade 2
Clubs 2
and so on...
How to achieve this. I thought of using wait/notify, but we've to some how make sure that each thread gets run in a particular order to print this.
In Basketball - score point system- 1 pointer , 2 pointer and 3 pointer score are valid. Given a team's total score ,you need to provide total number of combinations that sums to team's total score. Ex:
TESTCASE 1: Team' score input:8, output:10
//(valid point in rule)*(no of such points)=(Total Score)
1*8=8; 2*4=8; 1*2+3*2=8;
1*6+2*1=8; 1*5+3*1=8; 1*4+2*2=8; 1*3+2*1+3*1=8; 1*1+2*2+3*1=8; 1*2+2*3=8; 2*1+3*2=8
A permutation is a list of K numbers, each between 1 and K (both inclusive), that has no duplicate elements.
Permutation X is lexicographically smaller than Permutation Y iff for some i <= K:
An operation "swap" means removing an element from the array and appending it at the back of the same array. Find the minimum number of "swaps" needed to sort that array.
Eg :- 3124
Output: 2 (3124->1243->1234)
How to do it less than O(n^2) ?
Mastermind is a game of two players. In the beginning, first player decides a secret key, which is a sequence (s1,s2,...sk) where 0 < si <= n, Then second player makes guesses in rounds, where each guess is of form (g1,g2, ...gk), and after each guess first player calculates the score for the guess. Score for a guess is equal to number of i's for which we have gi = si.
For example if the secret key is (4,2,5,3,1) and the guess is (1,2,3,7,1),then the score is 2, because
g2 = s2 and g5 = s5.
Given a sequence of guesses, and scores for each guess, your program must decide if there exists at least one secret key that generates those exact scores.
Input
First line of input contains a single integer C (1 <=C <= 100). C test-cases follow. First line of each test-case contains three integers n,k and q. (1 <=n,k <=11, 1<=q<=8). Next q lines contain the guesses.
Each guess consists of k integers gi,1, gi,2,....gi,k separated by a single space, followed by the score for the guess bi (1 <= gi,j<=n for all 1 <=i <=q, 1 <=j <=k; and 0 <= bi <=k )
Output
For each test-case, output "Yes" (without quotes), if there exists at least a secret key which generates those exact scores, otherwise output "No".
Sample Input
2
4 4 2
2 1 2 2 0
2 2 1 1 1
4 4 2
1 2 3 4 4
4 3 2 1 1
Sample Output
Yes
No
which is the best way to find most significant 1 in binary representation?
Given a array of integers , find 3 indexes i,j,k such that, i<j<k and a[i] < a[j] < a[k]. Best possible is a O(n) algorithm.
Write a function to determine node in a tree at maximum depth , with ties to the right ( ties to the right means , right most node at MaxDepth D )
Given an arrangement of balls on 2-D Euclidean plane (i.e a flat surface), you have to assign a color to each ball
such that no two adjacent balls are of the same color. A greedy approach can be used to reduce the number of
colors required.
Question:
Model this as a graph problem. [Hint: Balls become vertices, adjacency relation is modeled by edges, and each
vertex has a unique identification number and a color.]. Write a program that finds the number of colors
required and outputs the balls (unique ids) along with their colors.. Note that to solve this problem, all balls and
their neighbors must be inspected.
Use adjacency lists to represent the graph.
The input to this program is a file containing the number of balls in the first line followed by the list of
adjacencies – one per line: e.g. an input line containing
x,y
denotes that balls x and y are neighbors. Here x and y denote the unique ids of the two balls.
A simple greedy algorithm for this color assignment problem is as follows:
I. Sort all the vertices in the graph on the basis of their degrees [This sorting should be done in-place on
the array of adjacency lists.]. Assume colors are ordered c1, c2, …
II. Let u be the un-colored vertex with the smallest degree. [Break ties in favor of the vertex with the
smaller id]
a. Assign first color ci in the list of colors to u such that
color(u) ci where ci != color(vj ) for any vertex vj in the adjacency list of u.
III. Repeat step II until all vertices are colored.
Implement your solution using a Graph ADT that supports the following interfaces:
a) Graph createGraph() : Creates an empty graph.
b) Graph addEdge(Graph g, Vertex v1, Vertex v2): adds an edge from vertex v1 to vertex v2 to the graph g.
If a new vertex is found, then an entry has to be added in the adjacency list
c) Iterator getNeighbors(Graph, Vertex): gets a list of neighbors of the vertex.
d) Graph sortGraphbyDegree(Graph) : sorts the adjacency list based on degree of the vertices. The vertex
with smallest degree will appear first, and the vertex with the largest degree will appear last. If two
vertices are having the same degree, then their order of appearance will not change.
e) Color chooseColor(Graph, Vertex): returns the first color in the list of colors that satisfies the condition
mentioned in step (2) above.
f) int assignColors(Graph) : invokes chooseColor vertex by vertex and stores the chosen color in the
corresponding vertex. This function returns the number of colors used.
g) printGraph(Graph , num_colors_used, file) : prints the number of colors used, num_colors_used, in the
first line of the output file. It then prints the graph into the file using the following format:
(vertexid,color):v1,v2,v3,vn
where vertexid is the unique id of the vertex, color is the color assigned to the vertex, and v1,v2,…,vn
correspond the unique identification numbers of the vertices that are adjacent to the current vertex.
Data structures Used:
Graph: This is a dynamic array, such that each entry in the array contains a pointer to vertex vi, the degree of vi
and a list of neighbors of vi.
Vertex: Each vertex contains the unique identification number of the vertex, its color.
List: This is for the list of neighbors, such that each entry in the list corresponding to vertex vi consists of a
pointer to vertex vj, ∀ vj Î neighborhood(vi)
Steps to perform:
1. Write the relevant Header files for an adjacency list representation of Graph
2. Write a driver file that reads an input file containing the edges in the graph and prints the graph after
coloring the balls. This driver uses the adjacency list for graph representation.
a. The driver takes the name of the input file and output file as command line parameters.
b. From the file, find number of nodes involved.
c. For each line in the input file corresponding to an edge
i. add the edge using call to addEdge().
d. The driver must then invoke function sortGraphbyDegree() to sort the vertices in the increasing
order of their degrees.
e. Invoke assignColors to assign colours to each vertex.
f. Print the number of colours used and the resultant graph into the output file using the call to
the function printGraph(). If no output file is mentioned in the command-line, then print the
graph into the screen.
3. Write the code for the functions a - g
You are given an array of n elements [1,2,....n]. For example {3,2,1,6,7,4,5}.
Now we create a signature of this array by comparing every consecutive pir of elements. If they increase, write I else write D. For example for the above array, the signature would be "DDIIDI". The signature thus has a length of N-1. Now the question is given a signature, compute the lexicographically smallest permutation of [1,2,....n]. Write the below function in language of your choice.
vector* FindPermute(const string& signature);
Input:
Given a hexadecimal value:
int i=0x3b24
Output: 0x243b
Some other case:
input: 0x123456
output:0x456123
A stream of numbers of length not more than M will be given. You don't know the exact length of the stream but are sure that it wont exceed M. At the end of the stream, you have to tell the N/2 th element of the stream, considering that N elements came in the stream. what would be best space complexity with which you can solve this problem
Why would you chose Java of C# to build your application?
The purpose of the Lo-Fi UI and storyboards is to debug the UI before you program it.
True
FalseThe purpose of the Lo-Fi UI and storyboards is to debug the UI before you program it.
True
False
What is a HashMap? What is one advantage of using a HashMap versus a TreeMap?
Given an array of integers, find the mode and the frequency of the mode. If possible, print each number along with its frequency.
In a hash map with objects as keys,
a) what method do you have to overwrite to do this?
b) how would you resolve a collision?
Write a program which makes use of two classes named integer and character. The class integer has one integer data
member lying in the private section and one member function named input lying in the protected section.The member
function input is used to enter the data in the data member.The class character publically inherits from the class
integer.The class character has one character data member and two member functions named calc and display.The calc
function ask the user to input data in the character data member which will be a number from 1-9.The calc function will
divide the integer number (Data member of the class integer) entered earlier with the number entered in the character
and the display function will display the message “Divides Completely” in the case the integer is divided completet and
the message “Does not divide” otherwise.The ASCII values of numbers 0-9 range from 48-57.Eg. run is as follows:
Enter Integer:10
Enter Character :2
Result: Divides completely.
Write a program which contains a class named String (please take care of the case). The class should be capable of
holding a string containing more than one word. The class should at least have a parametric constructors by which we
are going to supply a sentence at run time. Class string should be defined in this way that the following statement
should be executed with their proper output.
String str1; //string with length 0
String str2;
cin>>str2; // to print the char elements of str2;
(Don’t use any string library function for the any purpose)
You are free to add any C++ concepts, any other data members, member functions and constructors you think are
necessary to solve the problem.
Write a program which contains a class named String (please take care of the case). The class should be capable of
holding a string containing more than one word. The class should at least have a parametric constructor by which we
are going to supply a sentence at run time. The class should contain a member function ‘palindromecheck()’which
reverses the words of the sentence in their proper original order. The class String should be user defined. You are free
to add any other data members, member functions and constructors you think are necessary to solve the problem.
Sample Run:-
Enter sentence:-
Mom…nothing can be better than you
Output:-
Sentence with reversed words is:-
you than better be can nothing …moM
Not Palindrome
Sample Run:-
Enter sentence:-
wife loves husband,husband loves wife
Output:-
Sentence with reversed words is:-
wife loves husband,husband loves wife.
Palindrome
You are free to add any C++ concepts, any other data members, member functions and constructors you think are
necessary to solve the problem.
Find out whether two strings are the same or not without using the equality operator nor the equals method.
.What do you mean by free pool in data structures
You are given an array of N elements.arrange array in such a way that sum of any cunsucative k numbers are divisible
by NUM.if not possible print -1.(it may possible that there are many solution possible then return any one)
For example:
N=6
k=3
NUM=63
array={80,17,90,82,27,19}
Answer:{19,17,27,82,80,90}
any 3 cunsucative no. like (27+82+80)%63=0
another solution={27,19,17,90,82,80}
may be a hint :try to group all no.'s in mod NUM map and use vector and map.
Find all elements in an array that appears 1/k times where k is any number such that 1<k<n. n is the size of array.
There is a given linked list where each node can consist of any number of characters :- For example
a-->bcd-->ef-->g-->f-->ed-->c-->ba.
Now please write a function where the linked list will return true if it is a palindrome .
Like in above example the linked list should return true
given y bytes and you can transfer only x bytes at once..give a mathematical expression having only + - / * which gives the number of iterations to copy y bytes. ( dont try giving modulo operator answers )
If you 15,000 HTML files, find all phone numbers in the files?
Last question and only asked to give general ideas!
Given two numbers, print all prime number between two given numbers.
what is hashtalbe?
How to use hashtable?
What is hash function?
How will you deal with hash space conflict?
Write a program to swap odd and even bits of a 32-bit unsigned integer with as few instructions as possible. (bit-0 and bit-1 are swapped, bit-2 and bit-3 are swapped and so on)
// I've created a thread that does some work and inherits from your base Thread class
class DoWorkThread : public <YourThreadClass>
{...};
int main(){
...
// DECLARE the base class
DoWorkThread example_worker ( data );
// Start the thread
example_worker.start();
...
<other calls you define that I would use>
}
Design a class (or several classes) to be used to implement C++ Thread Management. You may use any
underlying thread library you choose (POSIX pthreads, Windows Threads, or some other open-source or
easily accessible threading library). Ideally your Threads should give me a safe method to pass progress
back to the main thread on the progress of the execution or my work that I’ve decided to perform with
your thread.
If something is unclear please note what assumptions you are making.
The following is an example of a test program that would use your Thread class
Design a class (or several classes) to be used to implement C++ Thread Management. You may use any
underlying thread library you choose (POSIX pthreads, Windows Threads, or some other open-source or
easily accessible threading library). Ideally your Threads should give me a safe method to pass progress
back to the main thread on the progress of the execution or my work that I’ve decided to perform with
your thread.
If something is unclear please note what assumptions you are making.
The following is an example of a test program that would use your Thread class
// I've created a thread that does some work and inherits from your base Thread class
class DoWorkThread : public <YourThreadClass>
{...};
int main(){
...
// DECLARE the base class
DoWorkThread example_worker ( data );
// Start the thread
example_worker.start();
...
<other calls you define that I would use>
}Design a class (or several classes) to be used to implement C++ Thread Management. You may use any
underlying thread library you choose (POSIX pthreads, Windows Threads, or some other open-source or
easily accessible threading library). Ideally your Threads should give me a safe method to pass progress
back to the main thread on the progress of the execution or my work that I’ve decided to perform with
your thread.
If something is unclear please note what assumptions you are making.
The following is an example of a test program that would use your Thread class
// I've created a thread that does some work and inherits from your base Thread class
class DoWorkThread : public <YourThreadClass>
{...};
int main(){
...
// DECLARE the base class
DoWorkThread example_worker ( data );
// Start the thread
example_worker.start();
...
<other calls you define that I would use>
}
Design a game of Tic-Tac-Toe. Only instead of 3x3, this is a game on n x n board. Two manual players play the game. A player wins if there are all "X" or all "O" in either of n rows, n columns or 2 diagonals. What are the classes and data structure you will define? After each move/turn of a player, it is checked whether the player won the game. Minimize this time. Assume having no space constraint.
Given a positive integer, decode it into a string in following way :-
1 - a, 2 - b,3 - c,...26 - z, 27 - aa, 28 - ab........and so on.
Given today is Thursday and 23rd August, 2012. Write a function to input a date (future or past) and tell which day it is:-
int day_of_week(int dd, int mm, int yyyy)
Mon -1, Tue - 2, Wed -3......Sun-7
With a pointer to head node of a linked list as argument, write a function to swap the consecutive elements of the list and return the head node. (Do note change values of any node, only change the links.)
Example :-
1->2->3->4->5->6->7
2->1->4->3->6->5->7
Given an array of integers, give the most efficient algorithm to find if the array has a majority element. If the array has a majority element, find this element. (Note : The majority element is the element that occurs more than half of the size of the array)
give you n numbers.each number is 0 or 1. output all possible arragement of these n numbers.give codes in C or py
Design a web counter to give how many hits per second, per minute and per hour (i.e., what kind of data structure and algorithm would you use to do this?).
Given a matrix represented as int[n][n], rotate it 90 degrees clockwise in-place. (In-place means minimal extra memory to be used, ie, don't make a new array to copy into). Rotate clockwise means top-row becomes right-column, right column becomes bottom-row etc.
State the difference between this two statement.
char str[] = "/root//foo/bar" ;
char *str = "/root//foo/bar" ;
Now, you have given an assignment str[in1] = str[in2]
where in1 and in2 both initialize with 0.
In first type of declaration no problem. But in second type of declaration 'Segmentation fault' is there. Why this happens?
Swap the nth node from beginning and nth node from the end in a linked list. You cannot just exchange data, you have to exchange pointers
Find the angle between minute and hour hand when time is 6:50 am
You have 8 identical balls and a weighing pan. One of the balls is fake. But you don't know whether it is heavy or light. Minimize the number of weighings
Divide a triangle into 5 triangles of equal area
A screen has different shapes of objects. The number f objects is large like million. We want to zoom into a region on the screen. How can we identify which objects should be displayed in the zoomed area? Give a data structure to store objects.
Write code to delete every Nth node from double linked list.
You have an array of size n with values ranging from 1 to n. Exactly one number is missed and one number is repeated. Find missing number and Repeated number.
Given an array of 100000 elements with numbers 15, 25, 35, 45 repeating. No other numbers are in the array. Sort the array with minimal space n time
given a character array of the form a[100]="aabbccc".You have to write an algorithm to convert it into
"a2b2c3" inplace.Try for O(n) solution.
WAP to print the node values of a binary tree
- Even level starting from right to left
- Odd level starting from left to right
Assume that level of root is 1.
a
b c
d e f g
Output: a c b d e f g
Assume you have a integer matrix (m x n) sorted over column wise & row wise. WAP to find the kth smallest element from the matrix.
E.g.
int[][] a =
2, 5, 8, 10
4, 7, 9, 12
6, 15, 20, 22
So 5th smallest element is: 7
Write code to sort an integer array of size N which has only three unique values 0,1,2 duplicated & randomly placed over the entire array.
- Memory used should be O(1)
- Run time should be O(N)
Assume that a binary tree is drawn over a Cartesian coordinate system (with X & Y axis) where the leftmost node is placed at point (0,0). So, we need to traverse the nodes and print in following manner:
For e.g., for this tree
a
b c
d e f g
Output should be:
d,0,0
b,1,1
e,2,0
a,3,2
f,4,0
c,5,1
g,6,0
Find the angle between the hands of a clock.
You are a startup trying to design a new mobile online music player.
(startup => you need to differentiate yourself from the existing music players)
An airline carrier is losing a lot of bags. You have been assigned to help them out. What would you do?
Write a program to read improperly indented C code from a file and add tabs and new lines as per convention in a new file. (Eg. After a control statement is encountered, print the opening brace on a new line. Then, on the line after that, increase indentation and begin writing code. Reduce indentation when a closing brace is encountered by the file pointer).
How do you sort a billion rows of data of integers (a few gigabytes) in a file with only 1024KB of main memory.
Qn below!
You are given an array of integers. Find all the combinations of the numbers of the array, that sum to another number(might be different for different combination) from the array.
One property of the array: The maximum number of the array will not be much greater than the others.
Sequence of steps that happen in CPU, cache, TLB, VM, HDD leading to execution of “x = 7” which isn’t present in cache or sysmem nor translation in TLB. Also specify if any intrs, exceptions or faults are generated.
Assuming you have three N bit unsigned integers a, b and c, what is the min number of bits you would need to store the result of a * b + c?
Regular Expression:
1. it should contain 8 characters
2. atleast one alphabet
3. atleast one number
Number and Alphabets may not be consecutive
Given:-
1) an array of strings.
2) a directed graph whose each node has a character
(graph may be cyclic)
count the number of occurrences of each string(given in array) in the graph.
int isBST2(struct node* node) {
return(isBSTUtil(node, INT_MIN, INT_MAX));
}
/*
Returns true if the given tree is a BST and its
values are >= min and <= max.
*/
int isBSTUtil(struct node* node, int min, int max) { if (node==NULL) return(true);
// false if this node violates the min/max constraint if (node->data<min || node->data>max) return(false);
// otherwise check the subtrees recursively,
// tightening the min or max constraint
return
isBSTUtil(node->left, min, node->data) &&
isBSTUtil(node->right, node->data+1, max)
);
Change the BSTutil function such that if root==null return false.
After changes the code should tell correctly if binary tree is BSt or not.
#include<stdio.h>
void main()
{int indx=0, a[5];
a[indx]=indx++;
printf("%d",a[indx]);
}
what will be the output?
Give a Data structure to store Name-value pair like name-age
"abc",12
"xyz",34...
such than insert(name,value), value = search(name), name = nthentry(n), delete(name); all can be perfomed in O(1).
Note:- after deletion order should be maintained.Ex.
"ds",12
"df",78
"teu",54
"etr",12
If delete("df") is called then nthentry(2) should return "teu"
There is one linked list having two pointer one as usual next and other is random pointer pointing to any random node in list.
write algo to make a duplicate of it.
Note:- Original list is const, Can't be modified.
give a string as a input(string should be one word)if the input string is multiple by 3 then print only the multiple of 3rd letter in the string, otherwise print the input. For eg: if input is Elephant, then print Elephant .
if input is Elephants then print eas.
Given an O(v+e) time algorithm to compute the path in a connected in unidirectional graph that traverse each edge in each direction exactly once.Describe how u can find ur way out of the maze if u r given a large supply of pennies.using JAVA
Find the nth node from the last of linked list using both recursion and iterative approach
Find the LCA of two nodes in a binary tree (not BST); ensure that both nodes are present in the tree; if not then error should be returned.
compare "write through cache" and "look aside cache"
You are at the center of n*n*n cube if n is odd and somewhere near center if n is even, print all possible paths to reach the surface of the cube
suppose a matrix A. find a element x in this matrix,x is the smallest in his line but the biggest in his column. Give codes in C
Sort an array of characters in linear time complexity (and linear space complexity if that's possible).
given m x n matrix print all the possible paths top to down.
Example
1 2 3
4 5 6
7 8 9
path for root(0,0) 1
1-4-7
1-4-8
1-5-7
1-5-8
1-5-9
similarly path for 2(0,1)
2-4-7
2-4-8
2-5-7
2-5-8
2-5-9
2-6-8
2-6-9
note- root 1 can go to middle down or right down since there is no left index available. if root element has left middle and right it can go to all those paths like 2 or 5.
follow up : provide the path which has maximum path sum.
code in java.
assume that dictionary has only 5 words...
APPLE,APE,BABY,BALL,CAT
write a program which will accept a string and list all possible words in the dictionary which start with that string.use binary trees for fast retreival in java
Write a C program to display * for each letter of password you type in command line.
Like:Password
********
implement adding two unsigned numbers without using "+" or "++"
>Compute the number of connected component in a matrix, saying M. Given two items with coordinates [x1, y1] and [x2, y2] in M, M(x1, y1) == -1 && M(x2, y2) == -1 && |x1-x2|+|y1-y2|=1 <=> they are connected
Example:
-1 0 -1 0 0
-1 -1 0 -1 -1
0 0 0 0 -1
0 0 0 -1 -1
0 0 0 -1 0
0 -1 0 0 0
0 -1 0 0 0
Output: 4. And they are:
-1
-1 -1
-1
-1 -1
-1
-1 -1
-1
-1
-1
My idea is to scan the matrix.
Initialization:
count = 0.
For every item in the matrix, do the following three tests.
(1) If it's 0, skip
> (2) If it's -1, check its four neighbors. If there is a neighbor whose
value is not 0 and -1, assign the value of this neighbor to the current item. Otherwise, `count++`, ant then assign `count` to the current item.
>
> (3) If it's not 0 and -1, assign the value of current item to its four
neighbors whose value is -1.
Can anyone help me verify this solution?
There is a stream of integers coming in. And you have to store top n elements. What data structures you would use?
1, The solution should be efficient such that n can be millions of integers.
2, Should be able to display integers in descending order. Sorting should not be done whenever requested.
3, Insert, Delete should be as optimal as possible.
Given a matrix with 1's and 0's, find the number of groups of 1's. A group is defined by horiz/vertically adjacent 1's.
Count number of instances of pattern in a string.
int CountInstance(string word, string pattern)
What the real problem could happen because of memory leak?? I have an adequate chunks of memory and I really don't bother how much memory wasted. Here what problem a memory leak can cause??
There is a boat on the water. There is a rock in it. At this time, assume the level of the water is L1. Now say, you threw the rock into the water and it reached the bottom. Now what will be the level of the water?
Give a basic over view of designing a linkedlist in Java
Given an Array say, a [0,1,2,6,3,4] and lets say x=5..
Return true for all the values which add up to value of x like 2+3, 1+4 etc; for everything else return false.
Given a list of strings, write an alogirthm that will return a list of sets of
* permutations.
*
* sample input: [abc, cab, ba, b, ba]
* sample output: [{abc, cab}, {ba}, {b}]
*/
How do we store data at x(Row),y(column) of an excel sheet into a 1 dimensional buffer of fixed size.
x can be any row and y can be any column..
you have Trie tree , not ordered , juts don't worry about the order.
write an efficient algorithm to Serialize and DeSerialize
the tree , in the same order , you need to construct the same tree.
what if the tree have millions of node ? optimize everything
-write an algorithm to tell if the tree is balanced ?
-what is the mathematics rule that can help us to define this? O(log(h)) , how to use this model in your algorithm
- what types of Balanced Tree ? Red-Black Tree.
write an algorithm to balance a tree ? and also to Auto balance a tree while you are inserting the nodes.
you have a table of 2 columns , describe task scheduler, tasks can't run unless other tasks it depends
on finished running
Task | Depend
-----------------------
A | B
B | C
C | D
and so on ..
from that table design an algorithm that output the task workflow execution in sequence.
A->B->C->D
it can be repeated , there can be loop cycle .
design an algorithm that output this in O(n) , space is not an issue.
anyway it was very though question you need to ask as many question as you know .
after this hard time , the solution will use a graph to represent the relation first
then you will traverse the graph to output the workflow.
in the final you need to have a knowledge of Topological Sort to be able to solve it.
so if you will not depend on luck try to study graph and graph algorithms very hard before you go .
you have a file with words , and we need to select top N repeated words in this file.
challenge Imagine this file is TB file that can't fit in memory what will you do?
Given 2 strings, return the max number that can be formed by joining them.
For example, if the strings are:
45 and 456
2 numbers are possible
45456
45645
The output should be
45645
Given an array and a key, sum min subarray whose sum is no less than key. O(n) Time needed
single machine,,given a dictionary(key->value),every entry takes 1KB,totally10 Million个entry,single mutex protecting the dictionary,mutex takes 512 Byte,What potential problems do you see and how would you address them?
Implement atof function. eg., +3.5e-2, .03e1, 1e1, 0.0
giving lots of intervals [ai, bi], find a point intersect with the most number of intervals
FInd the maximum sum of a sub-sequence from an positive integer array where any two numbers of sub-sequence are not adjacent to each other in the original sequence. E.g 1 2 3 4 5 6 --> 2 4 6
You are given intervals of contiguous integers, like [1, 10), [15, 25), [40, 50), which are non-overlapping and of a fixed size.
Design a data structure to store these intervals and have the operations of insert, delete, and find functions
You are going to take some numbers as an input from a file. You need to witer a program to find longest increasing sequence. You should process it as soon as you are taking an input. After finishing the last input immediately you should be able to tell the sequence. Input: 1 5 3 4 6 4 Output: 3 4 6
Design the Facebook Credit system which is a application where users can buy/trade virtual currency and can use the virtual currency to purchase Facebook services, like paid apps.
Design and implement an algorithm that would correct typos: for example, if an extra letter is added, what would you do?
design and implement algorithms that correct typos, offering guidance, encouragement, and confirmation along the way
Given a binary tree find the difference in height between the closest leaf to the root and the furthest leaf from the root. You cannot use recursion since the tree is very deep and would cause a stack overflow.
assume that dictionary has only 5 words...
APPLE,APE,BABY,BALL,CAT
write a program which will accept a string and list all possible words in the dictionary which start with that string.use binary trees for fast retreival in java
A queue is implemented using a circular list. If only one pointer is given to which node a pointer p should point such that enqueue and dequeue operation could be performed in o(1).
options are
1) Rear
2)Front
3)Node next to front
4) one more option was there
There are three operations on a stack. push, pop and one extra operation reverse that will reverse the element in stack. Using this we have to implement a queue. so for Enqueue and Dequeue operations how many operations on stack are needed.
options are
1) 3,3
2) 1,1
3)1,3
one more option was there i don't remember
Given a binary tree, where each node has some value.
Print the path with maximum value.
Designa a phone book - basically contact book on phone.
Give data structures and give time complexity to search a phone number.
Ex: search - freeninza and if found in your phone book return the mobile number of user.
Given 2 strings find if they are anagram
what trick would make the bit string algorithm generate subsets in squashed order?? squashed order demands an arrangement http://www.scribd.com/doc/59300888/64/Generating-Subsets
Build an HTTP Library that is common and can be used by various clients like Twitter, Gmail, facebook etc. What features would you add into this library
Longest posibble path in a tree, you had to return the end leaf nodes.
geeksforgeeks(dot)org/diameter-of-a-binary-tree/
Write a menu driven C++ program to display area of circle, rectangle, and triangle
using function overloading. (overload area function)
Function Overloading
1. Area of Circle
2. Area of Rectangle
3. Area of Triangle
4. Exit
Enter Your Choice: 2
Enter the Sides of the Rectangle: 5 5
Area of Rectangle is: 25
1. Area of Circle
2. Area of Rectangle
3. Area of Triangle
4. Exit
Enter Your Choice: 4
Given two strings A and B of different length, find that whether all the characters of A exists in B or not.
For example,
1.
A: 'abcd'
B: 'agbchd' ===> letters of string A exists in B.
2.
A: zzz
B: abz ==> letters of A exists in B.
Given a string with duplicate character. Tell its rank among all its permutations sorted lexicographically. Spcially mentioned that string contains duplicate characters.
Given an integer array, sort the integer array such that the concatenated integer of the result array is max. e.g. [4, 94, 9, 14, 1] will be sorted to [9,94,4,14,1] where the result integer is 9944141
Print a binary tree in vertical.
e.g.,
1
/ \
2 3
/ /
4 5
\
6
o/p: 4 2 1 5 3 6
how to sort a single linked list with out using an additional node?
How would you implement PIPE functionality in UNIX systems. Like "tail -f xyz.log | grep amazon"
How would you implement trending topics for twitter. Think at large scale as well.
Please elaborate your assumptions as well.
Design a system where you can reutrn top 20 queries made in last 24 hours to users.
Think on the scale of Google and Yahoo. How would you store data. What will be your data structures, algorithm to get that data.Describe your assumptions etc.
For simplicity, you can assume that every web server create a log file with query and timestamp.
A legend among a group of n people is a person who is top rated in all respects.The task is to identify a legend by asking a single question of the form "who deserves it?" Design an efficient algorithm to identify a legend or determine if the group has no such person.How many questions does your algorithm need in the worst case??
Implement the classes to model two pieces of furniture (Desk and Chair) that can be constructed of one of two kinds of materials (Steel and Oak). The classes representing every piece of furniture must have a method getIgnitionPoint() that returns the integer temperature at which its material will combust. The design must be extensible to allow other pieces of furniture and other materials to be added later. Do not use multiple inheritance to implement the classes.
You have an API for compressing 64 Bytes block of data. How would you implement products like zip/winzip/gzip etc from that.
You can assume that to compress a larger file you can just add compressed block of smaller parts.
Please write your assumptions clearly. Be it system etc.
What is the base complexity of inserting an item in Binary tree?
What is the base complexity of searching an item in
a)Selection sort algorithm
b)Linked list
c)BInary Tree
d) Hash table
e) Queue
Find the subsequences whose elements should not be adjacent and their sum should be maximum from the given array (contains only positive integers).
Eg: int[] A = {10, 1, 3, 25}
Sol: Sum: {10, 3} = 13
{1,25} = 26
{10,25} = 35
Here the Maximum subsequence is {10, 25}.Find longest palindrome sequence in a given array.
Ex- 12345gsfggd541fhgs54321fgsdh
Ans- 12345/54321
Write a program to determine whether n/2 distintinctve pairs can be formed from given n integers where n is even and each pair's sum is divisible by given k. Numbers cannot be repeated in the pairs, that means only you can form total n/2 pairs.
How would the Destructor for Singleton look like ?
dbx and how to debug a multi threaded application
Use of virtual destructor
Practical usage of STL set.
find number of x such that C(1000000,x) is divisible by 401
Given a Matrix of M by N, each cell containing 0 or 1. Find the max contiguous trail of 1's. (trail could be horizontal, vertical or diagonal)
We have a long chain of cuboids in all the six directions (six faces). One start node is given and one end node is given. Give a data structure to represent this also search for the given node from start node.
Given 2 arrays A,B, where x(A.length) < y(B.length), we want to
insert (y - x) 0's to A at various places such that A*B is minimum. For instance, if A = (1, -1) and
B = (1,2, 3, 4), then inserting two 0's in the middle of A such that A = (1, 0, 0, -1) would minimize
A*B. I think he was looking for a dynamic problem solution.
A period of time where users login and logout, given a sets of login and logout time pairs, write a function that can show the number of users online at any given time.
Implement a read/write lock, given a mutex that has lock() and trylock() interface
You have a file consists of billions of records.
It cannot fit into memory, so you need to reverse every word in that file and save to another file.
estimate the back-end capacity for mobile check in feature
write an iterator function that returns next node in inorder traversal sequence in binary trees. You can write an init() function to initialize what you need
Find the sub array from an array of positive numbers where sum is maximum and numbers that are selected are not adjacent
Given a number, find next higher palindrome number that comes after this number. Give algorithm.
123
456
789
*0# matrix is given .This is the mobile keypad. User can dial horizontally and vertically number. For example if User dial 1 then next he can dial 2,3,4,7 only.
Question: Find the all possible 6-digit no. user can dial.
Constraint: No can't be start from 0. And charter * and # should not be included in six digit no.
Please give the suggestions.
Given an unsorted array.
With each number, we can associated a sum which is equal to the sum of all the numbers, less than the current number.
We've to find the total sum of all those numbers.
e.g. unsorted array :1, 5, 3, 6, 4.
for a[0]=1, sum[0]=0
for a[1]=5, sum[1]=1
for a[2]=3, sum[2]=1
for a[3]=6, sum[3]=1+5+3
for a[4]=4, sum[4]=1+3
total sum =sum[0]+sum[1]+sum[2]+sum[3]+sum[4] = 15
Write the recursive implementation of DFS and BFS for an n-ary tree. Tree node has an int data item, and a linked list "children" of nodes.
Write a program to traverse and return all nodes of an n-ary tree(note: not a binary tree).
Given an array of integers,which is sorted and then rotated,
Find the index where the rotation happens
Given a binary tree,Sum all the values of leaves .
Find the first common ancestor of two nodes in a binary tree (note not a BST).
In Excel sheet rows are marked using integer numbers like 1,2,3 but the columns are marked using characters. Like A, B and C.
so here column 0 = A (assuming column starting with 0)
column 1 = B
column 25 = Z
column 26 = AA
column 100 = CW
Q. Write a program to give the string representation of column for given integer.
Given a sum find(print) all 2 numbers and their index positions from an un-ordered array that add up the sum value. 1 4 4 3 7 5 8 as array and sum =8 .
So here the code should print 1 (index 0) + 7(index 4)
4(index 1)+ 4(index2), and so on..
How do you test a Calendar? (eg. An outlook calendar or google calendar)
Rotating K times a Linked List
Given: k=3
LinkedList: 10->20->30->40->50->60->70->80
Output:
Sry, I dont remember the exact output as the list was almost zigzag sorted like:
30->40->10->20->60->50->70->80
any possibles hunches for a valid qn...?
Sort the Arrays without using extra spaces.
Input:
Array1 = {5,4,6};
Array2 = {13,2,1,18,[] ,[] ,[]};
Output:
Array2 = {1,2,4,5,6,13,18}
Print a rectangle on screen only if it doen't intersect with other rectangles which are already drawn on screen.Minimise number of comparisons
Note :- the rectangles are axis-aligned
Write a code to generate Pascals triangle of any level.
If there are two threads in your app - T1 and T2. T2 has high priority. However, for some reason the priority decreases automatically. What could be the reason? How will you debug it? How will you fix it so that pririty stays the same, no matter what.
how to find second shortest path in graph?
Generate all possible combinations (of r elements) inside an array of size N
E.g. arr [] = {2,8,14} All possible combinations of r=2 will be {2,8}, {8,14}, {14,2}
Print an order of all the knight moves such that it fills up an 8 by 8 chess board. The moves should be such that no block that has been stepped on is visited again.
I have a list of N teams T1, T2, T3 … Tn. Each of these teams has played a match against every other team. I have a function displayResult(Team T1, Team T2), it returns the team which won the match between any two given teams T1 and T2.
I have to write the teams in an order such the (n-1)th team (in the order) had lost to the nth team which in turn had lost to (n+1)th team..Write Code
Find the mean and median of the elements which are dynamically added at runtime.
Given a sorted but rotated array. Search an element inside it without finding the pivot. Complexity of the solution should still remain O(Log n)
Given a sorted but rotated array. Find the pivot.
How will you implement a stack using a priority queue. Push and pop should be in O(1).
What data structures will you use to implement a text editor. Size of editor can be changed and you also need to save the styling information for all the text like italic, bold etc.
Generate a random 4 letter word from /usr/share/dict/words
A file contains a billion integers, try to find any one integer that is not in the file.
How would you implement hash table on your own? Write the code for implementing your own hash table?
If you wanted to make a highly concurrent cache with a least recently used replacement policy, what data structures would you use? How would this scale per number of threads?
Given an array { -2 3 5 0 -3 7 -1}. Sort the array in such a way that array should contain -ve numbers first and then zero and then all +ve numbers. (Note: order of +ve number and order of -ve numbers should be same after sorting). For ex: the o/p of above array is {-2 -3 -1 0 3 5 7}
Given 3 sorted arrays. Find(x,y,z), (where x is from 1st array, y is from 2nd array, and z is from 3rd array), such that Max(x,y,z) - Min(x,y,z) is minimum.
write an efficient algorithm to find whether a given number is a perfect square.
eg: 4 is a perfect square of 2. 5 is not a perfect square.
note : the input number can be very high.
Write a function to convert a decimal data to a binary data.
A web site log file contains user sign in information. What data structure you will use to store the user sign in information so that it is easy to find out whether a user signed in in the previous date? (I asked to clarify the user sign in information data format. The answer is a string (?))
How to calculate a mathematical expression stored as a string ? for eg :- string = "4* ( 3 + 2 ) - 1"
I have an arrayList A which contains say 2,3,5,7,8
I have another arrayList B which contains 1, 3
Now taking the elements of B as the locations, I need to remove the elements of A present in that locations. So, basically I need to remove the element 2(position 1) and 5(position 3) from A. How to achieve it as we know that once one element got removed from an arrayList,the positions will be auto adjusted.
Design a chess game. Basics of a chess game was explained and a player could be human or AI.
Follow-up questions:
* What are the main objects?
* How do the main objects interact with each other?
* Which object or objects own the current game state information?
* Implement the method to move a piece to another position on the board. method must communicate if the move is legal or not.
* How do you test the move piece method?
Write a C function to remove all spaces from a string.
Follow-up question: Explain the space and time efficiency of your solution.
A well renowned hotel has three branches in Miami. Namely x,y and z.Each has two types of customers. Regular and Rewardee. Also each branch has its own ratings x is given a 3 star rating while y has 5 star rating and z has 4 star rating.
write an algo to swap the pairs of a linked list
Write code for Queue operations add an element to queue and delete an element from queue. Time complexity should be O(1). Queue should be handled using an Array.
Algorithm to solve Crosswords puzzle
to fill with random words from a dictionary and explain complexity of Best/Worst and average cases.
Requirements:
- Layout of the board
- rules which says length of each word need to be filled at a position (either horizontal or vertical).
- Words need to be taken from Dictionary (design your own data structure to handle dictionary)
- General field validations need to be considered.
find path from root to leaf nodes in iterative fashion.
Describe Class diagram of a Card Game like Poker. What classes to be used. How to deal and shuffle the cards in cards class
Design a Date class that represents a US date. Write add and subtract operation using the class. Optimize the operations.
Write a function that given a Binary tree, can find out if its a Binary Search Tree
given an array of numbers and a number X, write a function that shows all the pairs of numbers that add up to X with in the array.
Giving a String, Write a function that returns the number of words in the string, It could have multiple white spaces at the front in the middle or end.
Describe an algorithm which, given n numbers, output the list of k numbers whose sum is maximum.
Your algorithm should run in O(n log k) time
Given a list L of integers, a1 , a2 , . . . , an , and an integer M , describe an algorithm that finds the largest
subset of L whose sum is at most M . Your algorithm should run in linear time
How we can perform insert, delete and findMax operations in O(1) time using a given queue ?
There 3 arrays A, B and C, all of equal length. C is the resultant array found using both A and B.
Suppose the size of the array is 3, then we need to find out the following.
c[0] = a[0] * b[1] * b[2]
c[1] = a[1] * b[0] * b[3]
c[2] = a[2] * b[0] * b[2]
I know the answer is pretty easy when it comes to brute force. But the wanted to know the answer with time complexity O(2n) and O(log n)
Note: O(n^2) is not acceptable.
Given an array of integers [2,1,3, 5, 7, 6], re arrange elements such that either even numbers in even locations or odd numbers in odd locations. i.e [2,1,6,5,7,3] in O(n)
#include <iostream>
class C {
private:
int num;
public:
C(int a) : num(a) {}
int get_val() const;
};
//changes are not allowed in below code
int C::get_val() const {
num++;
return num;
}
int main() {
C obj(29);
std::cout << obj.get_val() << std::endl;
}
The question was to make the above code work you can make changes only inside class C
given string is of the form "abcd1234defgh8965" then output should be "a1b2c3d4 d8e9f6g5" with O(n) time??
Given an array [a1b2c3d4] convert to [abcd1234] with 0(1) space and O(n) time
There is a job which would comprise million of tasks. There are multiple JVMs. Design a system such that these tasks are shared across JVMs.
Say, I have two classloaders in same JVM, CL1 & CL2.
CL1 loads class A & CL2 loads class B
A wants to access B. But I don't want to load B again in CL1. Is it possible for A to access B, when both are in loaded in different classloaders?
Design Solar System
Given four resources A1, A2, B1 , B2. Such that Thread T1 and Thread T2 operates on A1, A2 and B1, B2 respectively. How will you ensure the order of execution is A1-B1-A2-B2 ?
Given 10 char wide two strings find if they contain same set of characters or not
I have to call a webservice and with that i need to send some data...how can i secure this soap call ?
N x N matrix where rows are sorted but columns are not. How will you search for an element ?
A n*n matrix is given which is containing elements in which each row alone is sorted. column is not sorted. I have to convert it into a single dimensional array which will hold all the elements of the array in a sorted manner
Given a string and a pattern('.' Matches any single character.'*' Matches zero or more of the preceding element.), find the first substring matching this pattern.
Write a program to nd the frequency of each terms in a given unsorted
array.
i have a file named as file.c
the content of the file is
hello<space>hai<tabspace>world<space>new<enter>
slelct<space space>@<tab>123<space>.......<tab>abc<space>12345<tab>abcde<space>****<space>finished.
i want to search any number after a selected string or any string after a selected number from the file by opening it... for example in above file if i selece string as abc it has to give 12345...
Given a unsorted array with n elements. How can we find the largest gap between consecutive numbers of sorted version in O(n)?
For example, we have a unsorted array
9 19 13 12 33 41 22
the sorted version is
9 12 13 19 22 33 41
the output of the algorithm should be 33-22 = 11
Write a program to count the number of uni-value sub-trees in a given tree. Explain reasoning, and implementation decisions.
Design a system similar to how tinyurl.com website works. Scalability, reliability etc. parameters should be stressed upon.
Given two lists sorted in increasing order, create and return a new list representing the intersection of the two lists. The new list should be made with its own memory — the original lists should not be changed.
For example, let the first linked list be 1->2->3->4->6 and second linked list be 2->4->6->8, then your function should create and return a third list as 2->4->6.
Given two numbers represented by two lists, write a function that returns sum list. The sum list is list representation of addition of two input numbers ?
Example First List: 5->6->3 // represents number 365
Second List: 8->4->2 // represents number 248
Resultant list: 3->1->6 //
Note :Any Carry forward should also be added as the new node . Any Comments on the code below
Given a matrix of n X n. You need to find any local minima.
Local Minima is defined as an element covered (neighboured) by the greater numbers.
For example - a[i][j]=4, then a[i+1][j] >4 and a[i-1][j]>4 and a[i][j+1]>4 and a[i][j-1]>4.
If it is a boundary element, only compare with its watever the available sides.
Complexity that they want is less than O(n2)
You have given n numbers from 1 to n. You have to sort numbers with increasing number of set bits.
for ex: n=5.
output: 1,2,4,3,5
Note: If you have two number with equal number of set bits, then number with lowest value come first in the output.
A tea vendor group starts at a railway
station. Each train arrives at different intervals
of time and each stays in station for certain
interval of time in which the tea vendor
can service the passengers. Each tea vendor
can provide service only for a specified interval
of time. Find an efficient algorithm which requires
minimum number of tea vendors so as
to cover the services of all the trains.
While travelling in a cycle race, there are
several pit stops. A cyclist can travel upto 50
km without stopping at any pit stop, where he
can have a health drink and refill his energy.
Given a start point ’t’ and let ’k’ be the distance
needed to be travelled by the cyclist, find
an efficient algorithm to reach the destination
’d’ so as to have minimum pit stops and prove
your algorithm is the most optimal one.
Given an unsorted array, how to divide them into two equal arrays whose sum of difference is minimum.
Can it be done in o(n)?
The maximum suffix of a string is the lexicographically largest suffix of the string. The maximum
suffix problem is to find the maximum suffix of a given string. Linear time algorithm required.
You are given n dices each with heads numbered from 1 to m. You are to throw the n dices and note down the sum of the numbers on each of the n dices. You'll be give a number x and its a win if the sum obtained is greater than x. The problem is the find out the winning probability given n, m and x.
Note 1<=n<=100,
1<=m<=10,
m<=x<=n*m.
Write a program to print the fibonacci series sum upto a particular no. using recursion.
If you are given 5 Sum= (0+1+1+2+3)=7
We are given a pre order traversal of a tree, contruct back the tree using that pre order Array.
Bitwise operator.
Add/Multiply two numbers using bit operation.
Program to write merge sort and explain the complexity.
When the storage in memory is done using Heap and when it is done using Stack.
Basically memory implementation through Stack and Heap.
Check whether the no. is multiple of 7 or not in best possible way.
You have an Array of a million numbers. Duplicates exist in the array.
Print out all duplicate numbers.
Give best way to do this.
How to perform security testing in the google page?
If we have given a data type, how can we find the precision value for this........need just an algo....
Generate a number is range (1,n) but not in a list (i,j)
for example range is (1,1000), list is [2,3,5,9,199,200,344]
Given a number represented as an array of digits, plus one to the number.
ie. 1000 is [1,0,0,0] result is [1,0,0,1]
How to check num is power of 2?
how to design a file system, which data structure?
How to check whether a integer is a prime?
An unsorted array of n integers, and range of integers are 1 to n. In the array, one integer has a duplicate , and one integer is missing. How to find the duplicate number and the missing number?
What if array are sorted?
How to check a loop in a link list?
Given an unsorted integer array, find the first missing positive integer.
For example,
Given [1,2,0] return 3,
and [3,4,-1,1] return 2.
Your algorithm should run in O(n) time and uses constant space.
Design a LRU cache? by O(1) insert, O(1) delete, O(1) search
how would you print the lever order of a tree (not a binary tree i.e. each node has more than two children)?
given a positive integer n, return an array n x n, and numbers increasing in spiral way using ***recursion***
for ex:
n = 4
return
1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7
What's the difference of Abstract and Interface class
Sort a hash table
given a binary tree and a value. Print all those path which sum up to that value. path need not to start from root but can contain root.
for .e.g
_________________5___________________
__________6____________7_____________
_____1_________2
in this tree for sum 9 the path is 1,6,2
for sum 8 the path is 6,2
for sum 20 path is 2,6,5,7
Implement a console based palindrome game where the input follows a sting and optionally followed by player's name.
Rules
-----
1. If the player enters a valid palindrome then increase the score by half the palindrome's length.
2. The game also lists top 5 Hall-of-Fame players based on the score ranks.
3. The game should register the player if not already registered.
4. If the server resets - then the players score should be reset to zero.
What is the data structure you will use to model Tennis tournament of size number of players n=8. Splitted into 2 groups? What is the complexity of finding the winner and the runner.
Given a sequence of integers, find the length of the longest ascending or descending sub-sequence.
eg : input {3, 5, 8 , 9, 3, -1, -4, -5, -6}
output : length = 6 (corresponding to the descending sequence {9, 3, -1, -4, -5, -6}
Given a matrix, write a program to print the elements in a circular way. Only two loops can be used.
eg :
1 2 3 is the input matrix.
8 9 4
7 6 5
output : 1 2 3 4 5 6 7 8 9
How to modify the file content using Java?
For eg--> I have a file that contains following data
1,21,Azhar
2,22,Ali
3,34,ABC
4,123,XYZ
.....
I want to modify the content of this file to:
1,Azhar
2,Ali
3,ABC
4,XYZ
Given a BST, maximum and minimum value, find the sum of nodes with values between the above range
You have an array in which half of the elements are identical, the other half consists of distinct elements. How to find the identical/distinct elements more efficiently than O(n)?
Write the code to find lexicographic minimum in a circular array, e.g. for the array
BCABDADAB, the lexicographic mininum is ABBCABDAD
Given an array. Find the number of inversions (if ith element is greater than jth element where i<j)
Eg: arr = {3,5,7,2,8}
Output: 3 ( 3>5, 5>2, 7>2)
Find the k'th shortest path between two given nodes of a graph
• Design the recommendation system for search keywords
• Design a system to support Facebook status update
Write an algorithm to find the ‘next’ node (e.g., in-order successor) of a given node in a binary search tree where each node has a link to its parent.
Write an algorithm that takes a file containing a sequence of lines representing all the folders in a mailbox where each line is of the form Id,ParentId,Name and produces a sorted hierarchy of folders with children indented from their parents and each line containing DisplayName:Id. For example if the input is:
4,17,Scott
1,0,Spock
17,0,McCoy
9,17,Kirk
Then the output should be:
McCoy:17
Kirk:9
Scott:4
Spock:1
Given a n*n grid map that is parallel with x, y axis, the down left point is (0,0),the up right point is (n,n). Given n rectangles, the down left point and up right point are (x1,y1)(x1',y1'),..., (xn,yn)(xn',yn'). xn,yn,xn',yn',n are non-negative integers, and all rectangles are parallel with axis. Design a query which return, for a specific grid unit (x,y)(x+1,y+1), how many rectangles cover it? Minimize the time complexity of the query and the pre-processing. 1<n<1000
Given tree integers a, b,c. Write a function: int median (int a,int b,int c) to get the median number among a,b,c. Can not use sort, the times of integer operations (e.g. compare, + - * /, bit computing) the less the better. Analyze the best and the worst situation.
How will you ensure mutual exclusion in Multi-core processors?
There is a bus stand. We have given arrival time of the buses and halt of every bus. timings can overlap. We have to find minimum no of platform on the bus stand, so that no bus has to wait to occupy platform.
In finding a loop in circular link list algorithm can we move the fast pointer by 3x, 4x or greater speed? if yes, when to use which one. How to find after how many cycle both the pointers will meet.
Design a system for showing quotes on the web?
For example, when the user is looking at page A, part of which is reproduced in page B, the system could highlight part of page A present the user with a link to page B.
What constitutes a quote?
How do you find quotes?
How do you make it scale to the web?
How do you handle updates?
How would you arrange the servers?
What data structures would you use?
FB has decided to award user who submits the billionth search query on a given day a car, by showing them a banner on their search result page. How would you implement such a system?
Given a 2-D array of 8x8 size. Each element contains a randomly generated integer > 0. You need to choose a 3x3 matrix from that. Now an algorithm randomly picks up one element from that matrix.
1) How will you maximize your chances of picking up the highest number?
2) Assume two players. Player1 selected a 3x3 matrix. Now after seeing that, how can Player2 choose a 3x3 matrix to maximize his chances of winning?
We have 2 data centers with equivalent datasets & a system that makes them approximately same. Ex table:
aaa.aardvark.com 10.10.10.10
bbb. ..
www.
Datacenter 1 has :
aaa
bbb
ddd
...
Datacenter 2 has:
aaa
ccc
ddd
...
zzz
We know data is never perfectly consistent and need to
find up to 100 errors (there are at most 100 out of a billion). We'd want to find bbb, ccc as inconsistent entries. How can we do a diff of a lot of data across an ocean?
Array is split rotated and the 2 splits are sorted. For ex: {7,10, 15, 1, 2, 4,6}. Find a given key.
Write Hash Table (with templates) and implement:
1) Insert(key,value)
2) Delete(key)
3) Get(key)
Focussed on collision resolution, chaining practices concurrency. I added locality of reference too speed up get(key).
Write a program to print the code structure.
(Basically it was to print the nodes of Tree in DFS. )
Write an API to find valid IP address.
(Asked followup questions like which kind or IP format, return type, range specific, etc.)
Design SkyDrive. (open ended question. )
Implement IEnumerable<string> foo(IEnumerable<string> a, IEnumerable<string> b) such that foo returns string in either a or b but not both
class base{}
class derived {}
main()
{
base b;
derived *d=dynamic_casr<base>&b;
}
it gives compiler error - because above inheritance is not polymorphic.
any reason why dynamic_cast, instead of returning 0 looks for polymorphic structure ?
Who initializes 'this' pointer ?
is it initialized before constructor call?
Given 2 sorted arrays..
find the median of the merged array without using extra space in O(logn)
what is the difference between
const int *i;
int const *i;
int *const i;
Given a set {1,2,3,4,5...n} of n elements, write code that outputs all subsets of length k. For example, if n = 4 and k = 2, the output would be {1, 2}, {1, 3}, {1, 4}, {2, 3}, {2, 4}, {3, 4}
Given a file of N bytes. Find a sub-string of minimal length that is not present in the file.
Given an N x M matrix having only positive values, we have to nullify the matrix i.e make all entries 0.
We are given two operations
1) multiply each element of any one column at a time by 2.
2) Subtract 1 from all elements of any one row at a time
Find the minimum number of operations required to nullify the matrix.
Note: no range of input was given
Is this possible?
A BST is given. Without using any extra memory AND WITHOUT USING recursion.
1. Convert the BST into Sorted single Linked List.
2. Convert the Sorted Linked List in (1) to exactly identical original BST.
Suppose tree is:
10
/ \
1 N
/ \
N 5
/ \
2 N
/ \
N 4
reverse a string in the following format :
kullu manali shimla
to
shimla manali kullu
there can any number of spaces in between the words in the string.
Given an array of Integers of size n, Find element appearing more than n/2 times
....
How to store a 100+ digit no. in a variable?
Unix command which will display content of file which has more than 45 characters?
Find the maximum element per level in a BST .?
In O(n) time and O(1) space ..? or O(logn) time and O(n) space.. telephonic interview
Swap two nodes in place without using any extra node. For example, if you have lists a->b->c then output should be b->a->-c- and so on..
Find out the square root of a double number. The result should be with in +/- 0.00001 of the actual result.
design the backend system(data structure) of facebook's "like" button
Write a non-recursive function to delete an entire binary tree.
Given a binary tree:
1
/ \
2 6
/ \ \
3 4 7
/
5
Given the pre-order, in-order traversals of the tree, reconstruct the tree.
Given a matrix with letters in each square and you have to find words which are there in the dictionary (like Children's Crosswords). You have been given a function which outputs 1 if the given word is in the dictionary. The word could be bidirectionally horizontal, vertical or diagonal. Write an optimal algorithm for printing all such words.
There are two sets A and B with n integers, write a program to check the whether there exists two numbers a in A and b in B such that > a+b = val ( val is given );
#include<stdio.h> #include<stdlib.h>
int main(){
union A {
long int y[5];
union B{
double g;
union C{
int k;
union D{
char ch;
int x[5];
} s;
}a;
}b;
}*p;
p=(union A * ) malloc ( sizeof (union A));
p->b.a.k=15;
printf("%d %d \n",p->b.a.s.x[0],p->y[0]);
}output : 15 15
plz explain with working
//what will be the output of the program if characters 'hello world' and enter are supplied to the program ?
#include<stdio.h>
int main()
{
void fun();
fun();
printf("\n");
return 0;
}
void fun()
{
char c;
if((c=getchar())!= '\n')
fun();
printf("%c ", c);
}output : d l r o w o l l e h
(plz Explain...)
Write a function called reverseReplace that takes three arguments. The first will be a string of many words, the second will be a single word that we are going to search for, and the third and final will be the string we want to replace the second word with. Example output:
reverseReplace("I like cats", "cats", "dogs") -> "dogs like I"
reverseReplace("I like cats", "mice", "dogs") -> "cats like I"You should test it against the examples above as well as a larger test suite.
Table: persons
id
first_name
last_name
favorite_ride_idTable: rides
id
nameWrite a query that will return the names and votes for the top 10 most popular rides in order from most to least popular.
Merge Two Arrays A & B where A has enough capacity to hold elements of array B. Also give the number of elements of A & B array. Follow Up- Test this code.
I need to test if the array is having -ve numbers also. Here is my code :
How do you test an application which has no logs no browser's? How do you verify test results ?
Why Amazon?
Which data structure would you use for optimum addition removal, querying and priority.
(Heap, Hash and BST were rejected )
ok after finishing the interview, he finally told me the answer: he said that with each node we must store the min and max child.
his opinion was: Hash has good insert query complexity, but bad priority wise retrieval.
BST has logn for all the operations
Heap just ensures that the top priority is at the top (not the next order)
no wonder i got a reject :P
Given a tree, link all the siblings from right to left.
Find the first occurance of a number in a sorted array.
How many unique BST can be made from a series of numbers 1,2,3,4,....n
The input is N
Given an array of integers, the function should return an array, with each position having the product of all other numbers than itself.
Corner cases have to be handled
Find the merging point of 2 given link lists...
I gave him the best O(n) solution i.e by first finding the length of both link list ..........
But he said that he doesn't want an efficient soln. but a soln which is original and cannot be found in any book or over the internet
How security is provided to each tab in google chrome? if there are multiple tabs open in Chrome, then how respective request goes in respective tab? (meaning the request of different tabs do not get mixed, how?)
How will you provide security to DB?
How will you search efficiently in DB?
what is diffarence between semop and semctl?
we can change the semaphores using both apis?what is the diffarence?
Given a string generate permutations of all possible lengths and print them in any order.
Now print the permutations in dictionary order.
What could cause a test case run on the same piece of code to pass sometimes and fail sometimes?
How do compare a case value with dynamic array of values in one case label
ex. select 10
case <A dynamic Array of integer >
<Do Something> break;
case 100 ....
end select
/*Find MagickNumber With Duplicate Numbers in Sorted Array 2. Consider a sorted array with all unique numbers. Where a magick number[i] =i */
/* -10,-5,2,2,2,2,4,7,9,12,13
* */
Why the MAGICK Index be on the left side ?
Need to Print all the elements of the ArrayList consisting an ArrayList using C# ?
Determine winner of 2/9 number game
Two players play the following game: they pick a random number N (less than 2 billion) then,
starting from 1, take turns multiplying the number from the previous turn with either 2 or 9 (their choice).
Whoever reaches N first wins.
The candidate should write a function that given N decides who wins (first or second player)?
Print all the elements of the ArrayList consisting an ArrayList using C# ?
Given an array of integers. Re arrange the numbers such that odd numbers occupy odd position and even numbers occupy even position. The order of numbers should not change and it is to be done in-place.
Given a file with a list of words, find 10 most frequently occuring words. Give most optimized solution.
how multithreading is achieved in multicore processors?
how many threads a process can have?
what are the disadvantage or problem in template instantiation?
There is a river and stones are distributed at certain distance .For example at x1 distance D1 stone present (Start-(x1)-D1--(x2)-.....Dn-2-(xn-1)--Dn--(xn)—end). We have given a value Z, which is much greater then sum of all distances (Z > x1+x2 ... xn). Question is to find out all possible patterns via which we can reach from start to end of river. Note Z distance required to be travelled, when we at end
If the head of a linked list is pointing to kth element, then how will you get the elements before kth element?
difference between synchronous and asynchronous io
send data from client to server using netascii mode.
using UDP.
just implement the sendto() and recvfrom() blocks.
suppose a structure :
struct item
char name[15];
int price;
long ID;
char type[8];;
if there is a server running on little endian 64bit machine and a client running on big endian 32bit machine how will client send the structure to server so that the problem of portability, endianness, and alignment does not arise?
client :
sendto(sd,(void *)&myitem, sizeof(item), 0, (struct sockaddr *) &server_addr, sizeof(server_addr));
server:
recvfrom();
what is the output of the following :
void crazy(int n, int a, int b)
{
if(n==0)
return;
crazy(n-1,b+n,a);
printf("%d %d %d\n",n,a,b);
crazy(n-1,b,a+n);
}
main()
{
crazy(3,4,5);
getch();
}
Explain with working ...
what is the output of the following :
#define SUM(X,Y)(X*Y)
#define MULT(X,Y)(X)+(Y)
int main()
{
int a,b,c;
a=2;
b=3;
c=SUM(MULT(a,b),SUM(a,b-a))-SUM(SUM(b-a,a),MULT(b,a));
printf("%d\n",c);
}
Implement a thread-safe Blocking queue in C/C++(POSIX) or Java
The aim is to find the optimal solution which packs the pieces in 4x4 unit square.
a jig saw puzzle is made up of exactly 4 pieces.
size of the completed puzzle is always 4 units x 4 units. This is given
There is no picture printed on the pieces; any solution would be valid, as long it is a 4 x 4 unit square.
The pieces can be only triangles, or quadrilaterals. Nothing else.
write integration testcases for gmail login page?
what is difference between clientserver aplication and web based aplication?example wit an example
write integration testcases for login page?
why vector does not push_front ?
given an array
int a[] = {0, 1, 1 ,0, 2, 2, 1, 0 ,1, 2, 1,0 }
to be converted into
{0, 0, 0, 0, 1, 1, 1, 1, 1 ,2 ,2 ,2}
inplace and single pass
design a distributed system to find the 1000th visitor of google.com
Design the backend for a Gmail-like mail system
design and implement a memcache
Design a DHT
How can I redirect the output obtained on console to a new file using JAVA?
You are given N unique numbers a1<a2<a3<...an. Find out the count of all possible binary search tress that can be constructed using these numbers.
for example with 3 elements 1,2,3 there are 5 possible BST and for 1,2,3,4 there are 14 bst
Hello Folks,
I have compiled quite a few good interview questions in the form of a book. Please go through the below link
http://bigjobhunter.blogspot.in/2012/09/dear-reader-it-gives-me-immense.html?showComment=1347514736672#c8544481386067351623
Magic squares:
A magic square of order n is an arrangement of the numbers from 1 to n^2 in an n by n matrix with each number occuring exactly once so that each row,each column and each main diagonal has the same sum.
Any other better approach than exhaustive search approach??? Even this is not working in many instances of n.
Create a doubly-linked list from the most bottom notes (leafs?) in a binary tree by re-using the left and right pointers. (that is the original text with a spelling error)
Design a site similar to tinyurl.com
Given a linked list that contains 0,1 and 2 . Sort this linked such that it contains 0s first, then 1s and then 2s in O(n) time. Remember its a linked list not an array.
You are given a tree (a simple connected graph with no cycles).You have to remove as many edges from the tree as possible to obtain a forest with the condition that : Each connected component of the forest contains even number of vertices
Your task is to calculate the number of removed edges in such a forest.
Sort 10^6 elements and the memory can take 10^4 elements at a time.
Write a class hashmap and implement: insert, get and delete (Open addressing/chaining). What points to be considered before going to production (focus on concurrency)
given a stream of quotes for a stock from the last trading day. Assume its already time sorted. Find the maximum amount of money you could have made on this stock by making at most N transactions. A buy and a sell is counted as one transaction. For parts N = 1, N = 2 and N = Inf and the generic solution for N = some number (open ended)
• Write a function that finds all the different ways you can split up a word into a concatenation of two other words.
range sum query,array,given i,j.
get sum array[i,j]:
requirement: n^1/2 space/time complexity
Any other faster way to solve the closest-pair problem than the one with the brute-force approach???
What is the difference between template class and class template ???
Write a program to identify the name of current city where you are using IP addresses.
To generate armstrong numbers ...In O(n)..
write a prog O(n) :
to interchange million rows to million columns in a file ..
Determine the absolute value of an integer without branching ( i.e. without using any if else statement etc)
Determine efficiently if an integer is a power of 2 without using any branching or loop.
Find the maximum and minimum of two integers without use branching (i.e. without using any conditional statements like if if else etc)
Given state of chess board, find whether its checkmate or not.
C# program to implement XML parsing.
difference between class and object.
program to connect to database and run a query.
Explain how C# class can be used by C++ class in .NET.
Program to test skills on Exception (apply try-catch-finally).
SQL Procedure and advantages.
SQL Index.
Principles of OOP.
Implement singleton
Overloading and overriding
Difference between interface and abstract class.
two BST are given find common elements in both....
given s string "1010101010" in base2 convert it into string with base4.not use extra space....
You are given n numbers x1,x2,x3,...,x(n-1) and x(n) and you can only do addition and subtraction operation with numbers, in how many ways can we get x1 S x2 S x3 S ..S x(n-1) = x(n) where S is from set +-
example X = {1,2,3,4,5,1}
possible solution 1+2-3-4+5
1-2+3+4-5
we have an array, and a window of k elements
which slides over n elements of array A
k<n
we need to construct array B
such that B[i] = min (A[i], A[i+1]....A[i+k-1])
we don't have additional space at all
and we need to work on a solution better then O(nk)
say n = (1,1,2,3,4,5)
k =2
b would be (1,1,2,3,4)
if k=3
b would be (1,1,2,3)
Suppose you have given a 2D array having filled with "L" or "W" i.e. either land or water, using DP you have to find it largest land unit in this grid, each cell of land is considered as 1 unit and you can only consider up,down,left or right land units as contiguous to each other not diagonal unit.
Example:
LLLL
LLWL
LWLW
WWLL
in the above mentioned grid the answer will be 8 units
how do i sort the list {do,while,for,int,if} in lexical order using selection sort??? Basically i am looking for ways to
handle the string.I mean should i first get the ASCII values of each of these and sort it accordingly???
Difference in memory allocation for struct & class and class & object.
Given encoded version of string like 'a2b2cd3' - It means string preceeding number is repeated digit number of times.'a2b2cd2' = 'aabbcdcd'
Input
You are provided a template in which you have to implement one function exploreString. The declaration of exploreString looks like
int exploreString ( string A, int k )
A is the compressed string.
k is an integer. find character at kth position.
In dynamic polymorphism,binding happens at run time.But virtual table is created and virtual pointer is initialized during compile time.when is the virtual table filled with the appropriate function addresses?
Given a string containing only digits, restore it by returning all possible valid IP address combinations.
For example:
Given "25525511135",
return ["255.255.11.135", "255.255.111.35"]{hint:recursion,backtrack}
Print a character 1000 times without using loop and recursion.
Just got out of my interview realizing how ridiculously stupid I answered this question. The question was there is an array of positive and negative integers. Write an algorithm to find the subsequence with largest sum of integers in this array. Also, I can not return the entire array, even if it makes the largest sum. If the largest sum is less than -1, throw an exception.
I made the mistake of ignoring negative numbers, thinking it would decrease my sum. :(
How is it possible to insert different type of elements in stack?
Given an array of integers. Print a pair whose sum is closest to zero?
Eg:
Input: arr = {2 5 8 -7 2,9}
Output: => 8, -7
Given: for every paper authored, there is a citation count vector. The h-index is a measure of researcher importance.
h-index: The largest number i such that there are i papers each with at least i citations.
1. Suppose that the citation-vector is sorted, how to efficiently compute the h-index?
2. Suppose that the citation-vector is not sorted, how to efficiencly compute the h-index? time complexity? an algorithm with time complexity n?
Definition w-index: The largest number i such that there are i papers, with the lowest paper having at least one citation, the next one has at least two citations and so on, ith paper has i citations.
The citation vector is sorted. How efficiently can you compute the w index? Code this
\e
Google is going to provide an over-the-wire service that the phone companies can use. This over-the-wire protocol will support three operations:
(1) void I_GAVE_OUT(n) -- the phone company is telling us that it handed out phone number (n).
(2) bool IS_TAKEN_(n) -- we are telling the phone company whether (n) is taken.
(3) number GIVE_ME_ONE() - the phone company is letting us tell them what number to hand out next.
ww
how to make a form which shows some text and there is some button but when you click on one button it , open another form in the same page and in that subform there is one submit button ,when you click that submit button then that sub form should disappear. thanks in advance
what is the difference between multi tasking, multi processing and multi programming operating systems with examples ???
Given a fixed length linked list(for example max elements allowed is 10), to add 11th element,Least Recently Used element must be removed from LL in o(1) time.
Given a 2D array containing only 0/1′s and each row is in sorted order. Find the row which contains maximum number of 1s.
Write a function to print a binary tree breadth first, left to right, starting for the lowest level
Eg. 1
2 3
4 5 6 7
should print
4567231
Given an array contains positive and negative values, find the subarray, whose sum is most closed to zero. Require nlogn time complexity.
given linked list a->b->c->d->e convert to
b->a->d->c->e without creating new node.
You are given N points in a X-Y plane. Find the two closest points out of them.
Give an algorithm to compute the root square of real number using basic math operations.
How will you implement tic tac toe game and write a routine that tests whether some one won.
given an array of integers find 3 numbers that sums to zero
Given a collection of numbers, print all possible permutations.
Then,told me the code is printing redundant combination.Make change so that one combination is printed only once
1,1,2
[1,1,2], [1,2,1], and [2,1,1].
given a list of integers, sort all odd position ints and put them in first half, and sort all even position ints and put them in second half, do it in place.
If you're given a list of countries and its corresponding population, write a function that will return a random country but the higher the population of the country, the more likely it is to be picked at random.
You have eight balls all of the same size. 6 of them weigh the same, and two of them weighs slightly more. How can you find the balls that is heavier by using a balance and do this in minimum number of steps?
what are the implicit member functions in C++ and JAVA ? and example
Generate a grey code sequence given the number of digits as input.
eg: input=2 output= 00 01 11 10
use minimum space and time complexity
write query to delete duplicate rows in MySQL ?
write a query to display top n salaries from employee table in MySQL ?
how to make form in same page while you click on button in php?
Why java is not pure object oriented language ?
Given an array of integers, find all combination of four elements in the array whose sum is equal to a given value X.
For example, if the given array is {10, 2, 3, 4, 5, 9, 7, 8} and X = 23, then your function should print “3 5 7 8″ (3 + 5 + 7 + 8 = 23).
Just Example : "Given 8 cue balls , one is weighing lesser than other 7. Find that(light weight) ball using just 2 chances on balance weight."
How to find a general solution to these kind of question? How to divide this set of balls? Is there any finer method or general formula?
Two trains enter at the opposite sides of a tunnel of length L with speeds 'V'. A particle enters the tunnel at the same time with a speed 'v' and it vibrates in the tunnel[i.e. if it reaches the end of the tunnel then it comes back]. What is the position of the particle by the time the 2 trains meet?
Write an algorithm to insert a new value into a circular sorted linked list.
Interview Question – how to improve a parallel cache, this is the most difficult question i got. I had no idea what the interviewer meant and he clearly had some 'right' answer in his mind, but no clue.
How would you store 1 million phone numbers?
Count the number of set bits for an 32 bits integer. How to improve the process for the second time use if the memory is unlimited?
On a 2-D grid, the positions (x,y) of 3 persons are given. Find the meeting point such that sum of distances of each person from meeting point is minimized.
Now generalize this to N persons and solve.
Write a program to find the (n-3)rd element in a singly linked list of unknown length in a single pass...
Write a program to find the middle element in a singly linked list of unknown length in a single pass...
implement ur own malloc() function, and free(), in C
implement ur own malloc() function, and free(), in C
Write an algorithm to check if a tree is complete binary tree or not.
struct tree {
int info;
struct tree* left;
struct tree* right;
} *root;
Write an algorithm to check if a tree is BINARY or not.
You are just passed the root of the tree.
struct node{
int data;
struct node *left;
struct node *right;
}
Given a plain binary tree, device a way to determine if it meets the requirement to be a binary search tree or not.
Give a good data structure for having n queues ( n not fixed) in a finite memory segment. You can have some data-structure separate for each queue. Try to use at least 90% of the memory space
Given a Binary tree (not the BST) , Produce the Ancestor matrix
Given an array of intergers. Write a program to print all the permutations of the numbers in the array. The output should be sorted in a non-increasing order. For example for the array { 12, 4, 66, 8, 9}, the output should be:
9866412
9866124
9846612
....
....
1246689
#include<stdio.h>
double fn(char *a , int b , char c)
{
return (1.1);
}
int main()
{
int it = 2;
char ct = 'c';
char a[30];
printf("%d\n",(sizeof(fn)));
return 0;
}
Why the output is 1 ?
Algorithm best suited to sort a linked list.
Write a C program to implement that algo.
normal bubble sort require 100sec to sort 10000 entries.what will be the input size if it will solve in 50sec.
Input: String array. The output of the method should be the String value out of the array passed in that contains the least number of numeric characters. If two Strings have the same number of numeric characters, return the longest String. If two Strings have the same number of numeric characters and are the same length, return the String that appears first in the input array. If the array is empty, return null.
How to write a program to find how many character in the string..
There is a linked list where some nodes have similar number. Sort them such that all the similar number nodes are cluster together.
Describe the difference between Chef and Puppet
I/P:1234abcd in array
O/P:1a2b3c4d
constraint:In-place.........with out using any extra buffers....though it's rational to use temporary variables. time comolexity o(n)WAP to find no of possible paths from source node to destination node. If connection between various nodes is given. If there exists a cycle in a path from source to destination print Infinite path else print total no of path. eg
5 8
5 is no of nodes
8 is no of connection
and connections are
1 2
1 3
1 5
2 5
2 3
3 4
3 5
4 5
nodes are 1 indexed. ( not 0 )
find no of path from 1 - 5.
ans : 6
There is given a string array and strings having names
for eg . careercup , career , dewdeals , onlineshopping
You have to create a program that finds the largest string in given string array
You have a book will billion pages. Each Page P has L lines and each lines has W number of words. Design a search algorithm which gives me best match search results. Best match is when all the words given by user exactly matches.
You came to a parking lot which is like a long road, which goes till very large length(say infinite length). Car parked on both sides of that road. You parked your car somewhere and forgot where is it. Write algirithm and then code to search your car. Note that- you dont know length of parking lot and you cant assume its length, you dont know where is your car, you are in middle of somewhere and your car might be in any side of the road
In unix, build a list of file-paths whose size exceed a given number of bytes.
In unix, gather a list of installed crons.
In unix, export a database, compress it, and send it to a network server - all in one line.
Manage n queues in a given memory.
Support below operations on queues.
//initialize n queues in memory m of size s
//queues will be identified with numbers from 0 to n-1
void initialize(void* m,int s,int n);
//enqueue object o into queue identified by q
//as long as there is free memory this should be successful
void enqueue(int q,Object o);
//dequeue an object from queue identified by q
Object dequeue(int q);
Give the best solution such that there will be minimum relocation of queues
you are given with the project of some newly constructed airport which has only one run-way for both take-off/landing flights. you should design the project in such a way that no two flights should collide with each other even in-case of system failure because life's of passengers is more important.share your design ideas.
Write a function that takes 2 arguments: a binary tree and an integer N, it should return the N-th element in the inorder traversal of the binary tree. I asked the interviewer if I could use a 3rd argument to store the result; he said okay.
there are 8 balls one is lighter than the others you can use a scale but you can only use it twice how do you figure out which one is lighter?
Given a char array find possible soln like :
eg for "abc"
ans: {a,ab,abc.b,bc,c}
char[] function(char[])
Given an integer array find the longest subarray cantaining consequitive nos.
eg {4,5,34,33,32,11,10,31}
ans is {31,32,33,34}
int[] function(int[])
Given a 2D matrix of characters we have to check whether the given word exist in it or not.
eg
bool function(char[][],char[])
s f t
d a h
r y o
we can find "rat in it
(top down , straight ,diagonal).. even in reverse order. with least complexiety.
Implement a hashset of size M for numbers.
Minimum candidate number will be 1, maximum candidate number can be N. (N>M)
I said simply to initialize an array of size N. when a number X comes in set Arr[X]=1. For lookup return the value of Arr[X].
He was fine with it, but asked me to give a better algorithm where initialization of array is NOT required. In above case we are assuming all elements of arr will be initialized to 0.
How can we do this any ideas ?
Re write the below program in such a way that it should print
Hi
Good Bye
******NOTE: You cannot change the main method*******
Class Program{
Public static void main(String args[]){
Try{
System.out.println(“Hi”);
System.exit(0);
}
Finally{
System.out.println(“Good Bye”);
WriteTestA class on such a way that the below program’s output should be false.
***NOTE: You cannot override equals method***
Class A{
TestA testObj = new TestA();
System.out.println(testObj.equals(testObj));
}
Two elements of BST are swapped by mistake. You have to restore the tree without changing its structure.
Design a system for the customer to review a product. It should be able to incorporate web-services. Describe the entire flow from the client to the database.
Convert binary search tree to doubly linked list
Given list of words in the order as in the dictionary, find the order of the alphabets.
Suppose you are given words in the same order as in the dictionary like a, ant, ball, cat, do, dog, fog, frock etc.
From these words you know that there are alphabets a, n, t, b, l, c, d, o, g, f, r, k.
You don't know the order of these alphabets before hand.
You will have to find the order of these alphabets based on the order of the given words.
From a and ant you cannot make out anything.
From ant and ball you can make out that a comes before b in the order.
From ball and cat you can make out that b comes before c in the order.
From cat and do you can make out that c comes before d in the order.
From do and dog you cannot make out anything.
From dog and fog you can make out that d comes before f in the order.
From fog and frock you can make out that o comes before r in the order.
From these clues you should make out the order of the alphabets.
Not necessarily you will be given all the dictionary words, but the words which are sufficient enough to make out the order of the alphabets.
You can always say you cannot make out the order if the words given are not sufficient.
u have 2 head pointers the 2 head pointer some where merged,how to heck merged or ot? is there any costly method?
if you draw chords at random in a circle what fraction of hem will be shorter than chords formed by an inscribed equilateral triangle
if you draw chords at random in a circle what fraction of hem will be shorter than chords formed by an inscribed equilateral triangle?
4)Input a number. Convert the number into words using return functions and regular expressions in Perl. Do not use parse functions.(15 => one five)
3)Input email address. Check if it is valid using return functions and regular expressions in Perl. Do not use parse functions.
2)Input a name. Check if it is valid (has atleast 3 letters and one vowel) using return functions and regular expressions in Perl. Do not use parse functions.
1)Input ip address. Check if it is in the range 172.125.1.0 and 172.125.25.0 using return functions and regular expressions in Perl. Do not use parse functions.
Input: two unsorted char arrays A,B(may contain dups) where A.length <= B.length
If each character in A appears in B, return true. Else false. Write the code.
what does 4 byte allignment in 32bit system mean.
eg :
struct
{
char a;
char b;
}
will it take 8 byte or 4 byte after padding.
char a - (1+ 3 for padding) char b (1+ 3 for padding)
so entire structure takes 8 byte?
or char a (1) char b (1 + 2 padding.)=4byte total?
doesn't 4 byte allignment mean all new var address should start with a multiple of 4.... ?
plz do help
Given two arrays A[6] and B[3], both the arrays have 3 elements each. Both of them are sorted, need to return the merged array A[] after merging with array B[]. Need to do this inplace.
Given an N by M matrix with values of N and M, and co-ordinates of a particular dot. Need to return true if the dot lies inside the matrix, false otherwise. Just develop the condition for this.
How to Achieve atomicity in Database given you are a database designer
There are 2 interfaces
Interface A
-> max()
Interface B
-> max()
Note:
max() have everything same signature are same in all respect
There is a class C which implements A and B
then what happens
> Compile time error
> Runtime
>No error it works fine
Given a binary tree and 3 nodes x,y,z, write a function which returns true if y lies in the path between x and z and false otherwise. Its been posted couple of times in past in careercup blogs, still couldn't find an apt solution which considers corner cases like
y
/ \
z x
3. What is size of the object created for this class in a 4-byte alignment, 32-bit system.?
Class A
{
Public:
A();
Virtual ~A();
Int a;
Char b;
Int c;
}If an array is having integers/Char/special Char... Ex: "PST456DA85M2A!!23++46", find out the sum of integers. ****Note: If we find consecutive digits in array we need to treat it as number, let say 456, we need to treat it as [ four hundread and fifty six]. Write a program to get the output by summing 456+85+2+23+46..also this needs to be done in lessnumber of iterations..
Write a C function to print all the elements less than the key element in binary search tree
There is a rectangular grid of size m * n . Bob is in location ( x, y ) inside grid. He can move in 4 directions up, down, right and left. He will die if he steps outside of rectangular grid. Find the probability that bob is alive given initial position of bob as ( x, y ) and number of steps he moves as N.
Edit : Bob moves one step at a time in all 4 directions but he can move N step starting from start state.
Given a BST, give an algo as well as code(C preferred) to change it into doubly linked list.
Given a doubly linked list, give an algo as well as code(C preferred) to change it into BST.
Given n circles in the plane, Determine whether any two intersect, in O(nlogn) time. Each circle is specified by its center and its radius, so the input consists of three arrays X[1..n],Y[1..n], and R[1..n].
Given a array, find the largest contiguous sub-array having its sum equal to N. ( optimal solution only)
Given a log file, extract all the lines starting with the word ERROR.
Given 2 strings - abcdefgh & cde - get the position from where the second string starts in the first string.(Do this inplace)
Determine the 10 most frequent words given a terabyte of strings.
Write down the various test cases for railway portal system. write the situation when it can crash.
find the number of occurrence of given sum in array
EX: input : 10 5 3 2 sum=15
output: 2
it means 15=10+5
15=10+3+2
There are n frames of m data element each. The data element in each frame is arranged in increasing order. You are provided m*n space in which you have to arrange all data in increasing order.
Time:O(n)
Space:O(1)
There are n frames of m data element each. The data element in each frame is arranged in increasing order. You are provided m*n space in which you have to arrange all data in increasing order.
Space:O(1)
Time:O(n)
Three strings say A,B,C are given to you. Check weather 3rd string is interleaved from string A and B.
Ex: A="abcd" B="xyz" C="axybczd". answer is yes. o(n)
output and why ?
#include<iostream>
class con
{
struct node
{
int data;
int rest;
};
public:
con()
{}
};
int main()
{ con c;
std::cout<<"size of con class ="<<sizeof(c);
return 0;
}: Design a data structure for the following operations:
I. Enqueue
II. Dequeue
III. Delete a given number(if it is present in the queue, else do nothing)
IV. isNumberPresent
All these operations should take O(1) time
what will be output ?
class z
{
};
class x
{
int a;
};
int main()
{
std::cout << sizeof(X) << '\n';
std::cout << sizeof(z) << '\n';
}design a
data structure which should occupy O(n) space and should be able to answer any range-minima query
in O(log n) time. without using TREE or heap
Given a binary tree, you have to convert it into a doubly linked list (inplace i.e you cannot use extra memory)
You are given a binary tree ( a general binary tree ) and not binary search tree, you have to find the node which is the lowest common ancestor of both these nodes. Can we perform better if it is a binary search tree?
Find number of characters in nth member in the following series.
A,B,C,D....,AA,AB,......,ZY,ZZ,AAA,AAB,............
e.g for n<=26 chars are 1 for n=27 it is 2
Additional Question: Find nth member
You are given many slabs each with a length and a breadth. A slab i can be put on slab j if both dimensions of i are less than that of j. In this similar manner, you can keep on putting slabs on each other. Find the maximum stack possible which you can create out of the given slabs.
Give the algorithm for the construction of right-pre threaded binary tree.
Given two trees, how do you find one of the tree is a subtree of other?
Remove all two zeros in the given string.
Example: a3409jd00dk000d
Output: a3409jddk000d
Note: If there are less/more than two zeros consecutive, it should not be replaced.
Find sub-array in an array of integers whose sum is maximum, integers can be negative, zero or positive.
Print the JSON text in an indented format.
Example: {A:"B",C:{D:"E",F:{G:"H",I:"J"}}}
Output as below
{
A:"B"
C:
{
D:"E"
F:
{
G:"H"
I:"J"
}
}
}
Find a raised to the power b, where both a and b are integers
Multiply two large integers represented in char array.
Find level wise linked lists in a BST.
Example: 1 has children 2 and 3
2 has children 4 and 5
3 has children 6 and 7
6 has children 8 and 9
then the algorithm should give the below
result[0] = 1
result[1] = 2->3
result[2] = 4 -> 5 -> 6 -> 7
result[3] = 8->9
Find common ancestor of two nodes which has least value.
There are n nodes with a value in each node.
Communication between two nodes can happen any time to pass the node value from one to the other, every communication takes 1 second.
Whenever communication happens from node a to node b, node b's value can be changed based on node a's value.
One node cannot participate in communication to two other nodes at any point of time.
At any point of time each node can hold only one value.
We need to end up with "sum of the values in all the nodes" as the value in all the nodes, how much time is required?
Check if circular open and close braces in a string are matching, braces can be nested.
Reverse double linked list
Merge two sorted arrays
int main()
{
char *a= "Novell";
char *b;
b=malloc(10*sizeof(char));
memset(b,0,10);
while(*b++=*a++);
printf("%s",b);
return 0;
}
What is the probability of being the answer correct for this question, when the answer is chosen randomly:
a. 0.25
b. 0.60
c. 0.25
d. 0.50
Given two string, check whether the other is permutation of first one or not.
Eg: box
xob Ans: True
Eg: box
obxx : Ans: False
This was simple one for Microsoft Developer profile.
Given a sorted doubly linked list, create a binary tree which is well balanced.
No example was given in the test.
Used the method similar to binary search.
Check whether a singly linked list is a pallindrome.
Eg: 1->2->1 Ans: True
1->3->2->1 Ans: False
I did it by using recursion in O(n) time.
Write a function in C/C++ that implements long2ip and ip2long in PHP.
Write a function in C/C++ that implements long2ip and ip2long in PHP.
Write a function to count the number of numbers between two 64 bit numbers a, b that have the sum of their bits equal to a fibonacci number. E.g Between 15 and 17 there are two numbers that have sum of bits equal to a fibonacci number.
If I want to make Tera Copy kind of software, ( using same functionality of OS, but changing some UI, n functionality) ? then how to do???
Any idea what to read for this work ?
implement the following interface in java :
public interface ExamImmutableQueue<E>{
public ExamImmutableQueue<E>enqueue(E e); /*returns the queue that adds an item into the tail of this queue without modifying this queue.
when this queue represents the queue(2,1,2,2,6)and we enqueue the value 4 into this queue.
this method return a new queue (2,1,2,2,6,4) and this objects still represents the queue(2,1,2,2,6)
*/
}
you are given a system of passing binary trees among 2 ppl
Step1: convert the tree to preorder and inorder strings
Step2:send those strings to the intended person
Step3:get back tree from the strings
whats your strategy of testing?write various test scenarios.---10 marks
We have a text editor application where we can choose 1)between 100s of
different fonts like arial, calibri, etc.. 2)different text sizes 3) different formatting such as bold, Italics, regular, etc..
Imagine that the application is similar to word(there we will have these options). Now give different test cases to test this application.
what pattern can we expect for microsoft written test? or like from what areas can we expect questions?
There is a big file of words which is dynamically changing. We are continuously adding some words into it. How would you keep track of top 10 trending words at each moment ?
Given two char arrays X="ZTANBMBLAUCY " and Y ="GABVCBKLAMNC", write an algorithm to find the longest subsequence that is present in both of them.
In the above case the common subsequence is "ABBAC".
Also describe the time complexity of your algorithm.
Generate a hashtable for storing the Phone book data having the tuples (Name, phone
number, mail id).
For the initial hash, you may use the hash function defined as (sum of ASCII values of all
the characters in the name field ) modulo m, where m is the size of your hashtable.
Compare the performance of the hashtable if
a) separate chaining is used,
b) open addressing with linear probing is used,
c) open addressing with quadratic probing is used.
given a n*n matrix A[]of distinct integers, find a index i,j such that a[i][j]<a[i+1][j],a[i][j]<a[i][j+1],a[i][j]<a[i-1][j],a[i][j]<a[i][j-1],
time complexity should be less than O(n^2)
An unsorted array is given, where there is no specific range in which the elements occur. There is only one duplicate element present in it. Let it is a[i]. It should be within the half of the size of the array from where it appears for first time. i.e. the duplicate element should be within (i+(arr_size/2)), at ith index it appears for 1st time. Find the duplicate element with minimum number comparisons.
how do you create a duplicate of a DoublyLinkedList in which the .next is okay but .prev can point to any node in the link list
double factorial of a number N
example: N!!
1)find first N factorial primes (not prime factorials)
write efficient program to find the sum of x^y + y^ and x^y - y^x and x^y/y^x and x^y*y^x
Given an array A of size 26*26. Determine whether each row and column of the array consists of set {a,b,c,d,.....z} where each element occurs exactly once
Test cases for finger print reader say in a laptop to login. Here you can swipe your finger to have a secured login. e.g. I will swipe my finger and the system will allow me to login.
find longest increasing sub sequence in 2d array.
(bit more expl..)
ex: finding length of the snake in snake game
---------
the sequence must not be diagonally.
but it can be any like top-bootm,bottom-left-top ........
increasing means one step
ex: 10,11,12,13 (correct)
12,14,15,20(wrong)
Ex: input: consider 4x4 grid
2 3 4 5
4 5 10 11
20 6 9 12
6 7 8 40
output : 4 5 6 7 8 9 10 11 12
given a float print the smallest float number keeping decimal position constant.....i.e. if number is 3120.434 smallest will be 1023.344....
function signature float funcName(float num)
if you have 10 records in table , you run query and got answer and next day data is inserted into table it becomes 12 records now i want to operation on only updated records (means 11th and 12 th records )
Given a string, find out whether the string contains any repeated characters or not. For example, 'abcd' does not contain any repeated character 'abcdaefgh' contains repeated character ('a' is repeated twice).
As part B, I was asked if suppose it is given that string contains no more than 20 characters, will you change your algorithm in anyway to improve memory/time performance. Then he specifically added that there is a constraint on memory.
design an efficient algorithm for
Suppose you are given a n×n matrix M storing numbers. You have to design an O(n3) algorithm to find
a sub-matrix whose sum is maximum sum over all possible submatrices of M. In C langauge
Design a crawler
constrains- a website can ban you if there are more than 5 parallel requests on that website at a time.
Given an array A storing n elements and a parameter k which is a positive integer, an element of A
is said to be k-majority of A if it appears more than
n
k
times in A. Design an algorithm which computes
a k-majority element, if exists, in array A. The algorithm must have O(nk) time complexity.
How would you design a client/server chess game, where clients can connect from multiple/different UIs?
Given a node in a BST, find the next biggest node. Node can be left child, right, root, etc. Code this.
You have a set of numbers from 1 to n+1. One number is missing; find the missing number. How about 2 missing numbers?
Write Preorder traversal of a BST, iteratively using a Stack?
write your own implementation of hashtable , write interface and implementation for same eg. get,put and delete function .
follow up question : suppose you have hashtable of size 4 and its full . you then delete 2 elements from it. how will you reuse the space . implement linear probing collision resolution technique in this hash table .
Suppose program's runtime is 12N2 + logn + 4000 . how will you denote this in Big O notation . no matter how big n is , you will always have 4000 added to it .
explain your big O too.
Given an array with positive, negative and zeros, arrange the given array such that negatives are on left, zeros in the middle and positives on the right.
if apple is for 40 cents, banana is for 60 cents and grapefruit is for 80 cents then what pear is for???
Given a doubly linked list with a data item, a previous and a next ptr along with another pointer "child" that may point to the head of another doubly linked list of same type(it will lead to a general tree type of structure) or it may be null. Flatten the tree into a linked list... minimum space and time complexity(order n). The doubly linked lists's head and tail are given.
You have a linked list in which each node is another linked list. How do you find the 7th most unique element in the among all the nodes in the most optimal time ?
Write a program which returns true if the given string contains the consecutive repeated substring .Ex-adabcabcd
here abc is consecutive repeated substring.
A string s is said to be unique if no two characters of s are same.
A string s1 is producible from s2 by removing some of the characters from s2.
A string s1 is said to be more beautiful than s2 if length of s1 is more than s2 or if both have same length and s1 is lexicographically greater than s2( ex: ba is more beautiful than ab)
Input: is a string which can be of maximum 10^6 characters, you have to produce the most beautiful unique string out of the given string.
I have 1 million queries on disk to sort, my local memory/catch can store up to 1 thousand queries, how can I perform sort?
what can be done if requirements are chaning continuosly?
Generating all unique Substrings of a String using Suffix Array (For making it a fast Process) in lexicographic order
in java.
Given a few numbers, how will you push them into a stack such that whenever I pop the top most element from that stack, I get the minimum number from the bunch. Also he wanted me to tell the pop push algorithm such that the order of insertion and popping should be O(1).
There is a set of 9 students and 3 schools Every school can be alloted atmax 3 students .Every school and student has its coordinates .Now we have to allot student in such a way that the sum of distance from all the student to the school should be minimum.
Given a head to linked list and integer as input, write a function to delete all matching elements in the linked list
Design Chess Game. asked me this in testing interview.
You have a circular Linked List:
a->b->c->d->e->c
Find where the cycle is starting
You have 2 sorted Arrays. A and B. A is shorter than B. B has few elements in sorted order and has space for all elements of A. Now Merge these both array so that All elements are sorted. You cant use extra Array. Use Only Array B.
Given a list of 'N' coins, their values being in an array A[], return the minimum number of coins required to sum to 'S'
[LinkedList] What's wrong with the code below under JDK 1.4? Fix it. How about JDK 1.5?
LinkedList[] ll = new LinkedList[3];
ll[1].add(1);
ll[1].add("red");
ll[2].add(2);
ll[2].add("green");
ll[3].add(3);
ll[3].add("blue");
The shortest code by character count that takes a single input integer N (N >= 3) and returns an array of indices that when iterated would traverse an NxN matrix according to the JPEG "zigzag" scan pattern.
For Ex
1 2 3
(Input) 3 --> 4 5 6 -->
7 8 9
Output--> 1 2 4 7 5 3 6 8 9
1 2 3 4
(Input) 4 --> 5 6 7 8
9 10 11 12
13 14 15 16
output 1 2 5 9 6 3 4 7 10 13 14 11 8 12 15 16Alice is a kindergarden teacher. She wants to give some candies to the children in her class. All the children sit in a line and each of them has a rating score according to his or her usual performance. Alice wants to give at least 1 candy for each child.Children get jealous of their immediate neighbors, so if two children sit next to each other then the one with the higher rating must get more candies. Alice wants to save money, so she wants to minimize the total number of candies.
merging two singly linked list without extra space (if one list is of 5 nodes and another of 4 nodes the resultant node will be of 9 nodes i.e you can not create node for third list).
how many times the base class are called in the following code.
class Base
{
}
class D1:public Base
{
}
class D2:virtual public Base
{
}
class DD: public D1, public D2
{
}
int main()
{
DD cObj;
}You have a matrix of size n*n with entries either 1 or 0. 1 means there is a path, 0 means no path. Find shortest path and print it from (0,0) to (n-1, n-1)
Implement Malloc() and free() functions. How is the allocation done? What data structures are used ? How will you know much memory has to be freed , like in free(ptr) , how much memory has to be freed?
write the function called and its definition body when a new is used??
Write a C function to implement Sierpinski Triangle
given function signature as
Sierpinski_Triangle(int incenter_x,int incenter_y,int len).
i xactly dont remember the wordings of the function declaration sorry
Given an integer value n find the next higher and next lower integer with same number of 1s as there are in the original integer n. Write C implementation of it
N*N matrix. contains only 0's and 1's.
every row is sorted in descending order.
find row containing maximum no of 1's. Efficient soln reqd.
This is a newbie interview question from Statistic industry.
there are a vector v {c1, c2,c3...c(n-1)} and a variable x, try to construct a polynomial eg:
p(x)= c1 + c2*x + c3*x^2 + ... + c(n-1)*x^(n-1)
For Winshuttle Written Test Search on YouTube:
Winshuttle Placement Paper
Given a doubly linked list which contains only 0 and 1(any number of 0 and 1). write a algorithm to sort them.
An additive sequence is 1,2,3,5,8,13
where T(n) = T(n-1) + T(n-2)
An additive sequence number is which when splitted in two different number forms additive seq.
Ex: 1235813 (split it 1,2,3,5,8,13)
Ex: 12122436(12,12,24,36)
A number range is given to you. Find the additive sequence number in that range.
Given a m * n matrix and value k. Find k * k matrix within the given matrix whose sum is maximum.
freinds can someone please xplain
N-Queen standard problem of DS
It goea like..how would you place N Queens on a N*N chess board such that no one can attack rest..
Please xplain logic..I have the code
Thanxs in advance/.........
Given an array of 32bit unsigned integers in which every number appears exactly twice except three of them, find those three numbers in O(n) time using O(1) extra space. The input array is read-only. What if there are k exceptions instead of 3?
Given an array of integer as an input. write a function to return the second most occurring element in the array.
you are given nos 1,2 ,3 ,4 ,5 ,6 ,7 ,8 ,9 u hav to form a 9 digit no such dat 1st 2 digits are divisible by 2,1st 3 digits are divisible by 3,1st 4 digits are divisible by 4 and so on..... (repetitions not allowed)
Which data structure will be used for storing a friend list for a social networking site..like facebook
Again part of "coding" test for non-programmers
What number is non-standard if standard means all integers.
Answers included 99, -0. 11.2, and -16. Unsure if -0 is an integer. No answer was an option as well.
Edit: that non-standard was not in the original question. I do not recall the question exactly, but it revolved around whether -0 is an integer.
A program removes all non-numeric characters until it reaches a second non-numeric and then stops. "+3.4"=3
What would result when "1.2" was entered?
1 was not an option. 1.2 was not.
No answer was an option. Chose no answer.
I did pass the test with many "no answers".
Which is a true statement?
if both true, A&B=True
A&B=False if only one false
A^B=True if only one True
Which of these 5 is not true? The all seemed fairly obvious except
1) A&B^C
2) 8&0+0=0
3 others I forgot
One was a math problem without an =
the challenge was not the logic but whether
one can classify an equation with 0=0 or answer 8 as
true or false.
No answer was available.
Updated
What is the remainder of normal fraction?
# = Modulo
Several problems used the # symbol defined as
the remainder 4 / 3 =1
One question asked 3 /4 another 1/2
another had 0/0
You had to know not only modulo but whether it
is usable for a normal fraction.
Please update if you take the test
update
Part of coding test for non-programmers.
‘ means not. It converts a character to null in a string but converts the character to 0 in an operation
1=John 2= Jane 3= Does
“’123” = ?
Jane3Does was the closest answer. It seemed wrong because of the 3 in there.
I'm sorry i forgot the other answers, but they were
equally illogical.
‘ means not. It converts a character to null in a string but converts the character to 0 in an operation
‘5 means null whereas ‘5+1=1
Which one of these is true?
Cannot recall the options; they all appeared false.
I put the last option, but couldn’t figure it out.
‘(‘5)=0?
Part of coding test for non-programmers.
Holy Water is concatenated by “Holy “.”Water” or “Holy”.” Water” Watch the space.
How would you spell "Holy water" given “Holy”=God and HOH=”Water”.
1) God.HOH
2) God.” “.HOH
3) God”.” HOH
4) Forgot others
Given a line, adjust this line to the page width.
For example, given "Dog is cute" (length of chars is 11) and the page width is 15, adjust the line to "Dog is cute". The extra spaces should be distributed as much even as possible. Assume there is no space before the first word or after the last word.
There is a lake, some hills and a dam. Also all these are at some heights (heights may/may not be same) which are also present. Hills numbered 0-9 (assuming for heights).
You can increase or decrease the heights of the hills and dam but not the river. The problem is to find the least cost to make a path from the lake to the dam through the hills. Also, height of A >= height of B for the water to flow.
u have a video file. the user watches some part of it. he may seek forward, backwards or watch same part again and again. you have given the intervals which he watched. find the fraction of the video he watched.
for e.g. 1-7, 10 -15, 5-11, 20-25 with total length of video being 50.
ans should be 2/5 or 0.4
u have an array of n integers. rotate it left by k positions. time complexity linear.
without using extra array.
you have given a function rand(3) which when called returns values 1,2,3 with equal probability. Derive a function rand(9) using rand(3) which returns values 1 to 9 with equal probability.
You have to count how many binary strings are possible of length "K".
Constraint: Every 0 has a 1 in its immediate left.
111011 <-- valid
0111 <--- invalid
111100 <-- invalid
if the end point of rectangular island is (w,z) and u are at (x,y) and u have to kill an animal which roam in that island , what is the probablity that u will not fall form the island to die , i.e. after the end point , and the possible moves are the 4 direction n/e/s/w (in Clock Wise). u have to code for it.....plz help guys
Given an array of n elements unsorted, find subset of the array making the max sum. Ex: {-2,-3,-5,40,-10,-10,100,1}
answer would be {40,-10,-10,100}
how will you test if the random number generator is generating actual random numbers
find degree of connection of two users in social networking site, like linkedin shows us upto 3rd level degree of distance.
so the aim is to find minimum degree of connection between two users.
by degree of connection i mean, say user1 is friend with user2 and user2 is also friend with user3
now user1 and user3 are 1st degree of connection with user2
and user3 is 2nd degree of connection with user1
if an array is given like 11
increment its value to 1
o\p should be 12
if the array has 99
o\p should be 100
you can use vectors.
given input
i\p : [1,2] [2,3] [3,4]
i\p: 2,3
o\p should be: [1,2] [2,4]
given an array of integers generate out put using product of N-1.
eg: if input is 1,2,3,4
output will be each product of other int in the array : eg: 2*3*4 , 1*3*4 ,1*2*4 , 1*2*3
solve in N not in N2 algo.
given an array of sorted integers with duplicate values , sort the array so that there are only unique values left in sorted order ( do not use any additional data type , do inplace sort )
Given a list of strings & string M28K, where M28K represents a string which starts from M , ends with K and has 28chars in between . Find if M28K is unique in the list of strings or not?
find degree of connection of two users in social networking site, like linkedin shows us upto 3rd level degree of distance.
so the aim is to find minimum degree of connection between two users.
by degree of connection i mean, say user1 is friend with user2 and user2 is also friend with user3
now user1 and user3 are 1st degree of connection with user2
and user3 is 2nd degree of connection with user1
Design an OO parking lot.
What classes and functions will it have. It should say, full, empty and also be able to find spot for Valet parking.
The lot has 3 different types of parking: regular, handicapped and compact.
Flattening the data: How to write a recursive function that returns a linked list of nodes, when given a binary tree of nodes? (The tree can be modified)
Write a function that would return the 5th element from the tail (or end) of a singly linked list of integers, in one pass, and then provide a set of test cases against that function (please do not use any list manipulation functions that you do not implement yourself).
If A and B, two integers are given.
compute A/B.
Ex. 2/5 --> Ans should be 0.4
225/1000 --> Ans should be 0.225
22/7 --> Ans Should be 3.(142857) where 142857 are repeating decimal
Given 2 rectangles with top left and bottom right coordinates for each rectangle, return 1 if they have a common area otherwise return -1
Code a distributed hash table that will always live on 3 machines. Optimize for the case where the 3 machines are virtual on a single physical machine and when they are 3 physical machines.
Explain rack awareness in a data-center and an application where it is valuable and another where it should be avoided.
What is the difference between random and pseudo-random numbers? Write two function that can generate numbers of the two types and prove randomness.
Mirror a binary tree. Second part involved mirroring without using a temporary variable.
Search a number in a large square but sorted matrix. Since the matrix can be very large, keep algorithmic efficiency in mind.
you have an array of strings . print all anagrams for a string with complexity n2 .
Suppose you have huge list of single digit integers how will you sort them ? list fits in memory . how can u do it with n complexity ?
how to sort 100 numbers given using memory size sufficient for 20 elements only(like array of size 20)
how to convert an english sentence into our native language sentence(given an dictionary of english-native language)..what data structures will be used for implementing dictionary and how to convert using it??
How will you implement your own rand() such that it returns an integer from 0 to n-1 with equal probability?
Find lowest common ancestor of two nodes in a binary tree iteratively.
Find the longest
subarray which consists of numbers that can be arranged in a continuous sequence.
For ex- {4,5,1,5,7,6,8,4,1}
output-{5,7,6,8,4}.Find the longest.
Given a stream of text eg you can read 1 char at a time, write fn that will return true if you can find a string str is in the stream before the stream runs out.Do not store the stream.
How do you find the first instance of a given number in a sorted array in which many of the numbers are repeated?
What is the time complexity of your code?
how will I acess the virtual methods with help of reference?? I dont have to use pointers..
Given the array of digits, you have to calculate the least positive integer value of the expression that could NOT have been received by you.
The binary operators possible are *, +, -, / and brackets possible are ( and ). Note that / is an integer division i.e. 9/5 = 1.
For ex- 6 6 4 4 the answer is 18
1 = 6 /6 + 4-4
2 = 6/6 + 4/4
3 = 6 +( 6/4) -4
4 = (6+6+4) / 4
……..
18 cannot be formed
how to construct a balanced binary tree? it should be based on the value of level given by the user
there is a stock comp whose stock prices are known to u of next 365 days. u have to write the code on which day u should buy how much stokes and sell how much stock. U cannot sell a stock until u havnt bought ny stock. write o program to optimise the profit...
What default method a empty class holds??
Empty calss in the sense class does not have any data members and methods..
How do you print the first k smallest elements from a large input array that even does not fit into the RAM? How efficiently can you solve it?
how to delete last node of a linked list by knowing only first node in O(1) time complexity?
if delete last then can we delete last second also?
You have a stream of bytes from which you can read one byte at a time. You only have enough space to store one byte. After processing those bytes, you have to return a random byte. Note: The probability of picking any one of those bytes should be equal.
Declare an array of N pointers to functions returning pointers to functions
returning pointers to characters? pls explain how to represent this ?
i am given two array character strings;
write a function to swap those strings.
char aaa[] = "hi"
char bbb[]="world"
is there any way to increase the size of aaa to 6 and bbb to 3 in the swap function?
Find the minimum element in a stack in O(1) time complexity and O(n) space complexity
Given a set of positive integers S = { a1,a2,a3,...,an} find two subsets s1 and s2 of A such that S2 = S - S1 and difference of | sum(S1) - sum(S2) | is minimum.
For example if we have a set S={12,4,7,1,6,3,3 }then S1= {12,6} and S2={ 4,7,1,3,3} such that sum(S1) - sum(S2) = 0 . It is not necessary that two subsets will always have the same sum.
Create a number pool 1...infinity which has 2 methods..
CheckIn(someNumber) and checkout()
Checkout should give the min number checked in.
Checkin should add to numberPool if number doesnt exist.
Intially all numbers 1..infinity are available.
eg:
1. checkout() gives 1
2. checkout() gives 2
3. Checkin(1)
4. checkout() gives 1 now.
You have a binary tree (not BST), serialize it in a stream and reconstruct the tree maintaining the format of the tree.
sending 2 streams InOrder+PreOrder or InOrder+PostOrder is not an option.
You are a hunter in the forest. A monkey is in the trees, but you don't know where and you can't see it. You can shoot at the trees, you have unlimited ammunition. Immediately after you shoot at a tree, if the monkey was in the tree, he falls and you win. If the monkey was not in the tree, he jumps (randomly) to an adjacent tree (he has to).
Find an algorithm to get the monkey in the fewest shots possible.
Print all combinations of M members of a set of N elements in a sequence such that each set can be obtained from the previous set by deleting one member and adding one member.
Count number of duplicated in a BST. Just print count at end or return count. Can't use HashMap or HashSet. Not supposed to any extra space
Example tree:
5
/ \
3 10
/ \ / \
2 4 8 10
/ / \
3 5 8
\
8Answer for this is 5 (1 extra 3, 1 extra 5, 2 extra 8 and 1 extra 10)
EDIT: tree can't be modified. No extra space should be used. It should be O(n)
We are given a list of numbers A= {5,9,12,16,25,30,45} and their fixed probability of occurance P={0.22,0.18,0.20,0.05,0.25,0.02,0.08} where sum(p) =1. The problem is to arrange the numbers in a binary search tree in a way that minimizes the expected total access time. Note: In a binary search tree, number of comparisions needed to access element at depth d is (1+d)
Given a number, find closest perfect square to the number?
Transform a binary tree to a left child right sibling tree?
Given a set of numbers. Print all possible subsets?
Given a circular single linked list.Write a program that deletes every kth node until only one node is left.
After kth node is deleted, start the procedure from (k+1)th node.
e.g.list is 1->2->3->4->5->1
k=3
1. You are at 1, delete 3.
List is: 1->2->4->5->1
2. You are at 4, delete 1
List is: 2->4->5->2
3. You are at 2,delete 5
List is: 2->4->2
4. You are at 2, delete 2
List is: 4
Return 4.
How efficient you can do it?
"Min(Max elements rows) not less than Max(Min of columns)"
can you tell me whether above statement ist true or false..
if it true, then tell me solutoin.
if it false, then tell me example
Implement user defined malloc().
Given a list of sets, return the smallest list of disjoint sets containing the same elements and the same groupings.
1. Write code , what is running time and space
Example: input1={2,1,3} , input2= {3,2,5,6},input3={2,4,6,7}
Output = {1},{2},{3},{4},{5},{6,7}
Solve T(n) = 2T(n/2) + 2.
How can i multiply and divide with only using bit shifting and adding?
eg. multiply a no with 46.
Which data structure will you use for implementing the dictionary. If hashing, list the hashing function you would probably use. If not,mention some other data structure !!!
Given the Pre-order of the BST .check if each non-leaf node has only one child.Linear Time is expected.
implement LRU cache in java without using built-in datastructure ie. linkedHashMap
how will you implement dictionary for client . suppose data is stored in database .you don't need to implement dictionary but explain entire interaction and systems involved .
The interviewer was not interested in knowing how dictionary is internally implemented . he was more interested in understanding bigger picture ie. high level , eg.
i explained you will have ajax call from client page to fetch matching words, explained arguments that i will pass in ajax , explained high level server side api , how this api will interact with db and how it will send information back to client .
i think we should discuss high level perspective eg. designing the system overall architecture rather than dictionary algorithm
steps involved to deploy a web services . interviewer was interested in high level tasks involved in deploying a webservices and how client will access it.
We need to sort 7 numbers each of 4 digits. What is the number of comparisons in worst case . Options are as follows:
1) 40
2) 38
3) 47
4) 280
Please also explain why so?
void Func(tNode **node){
if(*node!=NULL){
Func(&(*node)->pLeft);
tNode *temp;
temp = (*node)->pLeft;
(*node)->pLeft= (*node)->pRight;
(*node)->pRight = temp;
Func(&(*node)->pRight);
}
}
what does this code do if root node of BST is passed to it? ny idea plz help
Implement rotate function for forward-only iterators.
Clarification: with O(1) additional memory. Rotate semantics should be that of std::rotate.
I personally know a O(n*log(n)) solution which takes O(log(n)) extra memory, and I assume it should be possible to reduce memory costs to O(1).
You have a database table Emp with data as follows:
EmpId FirstName LastName
1 Bob Lync
2 Sarah John
3 Bob Lync
4 John Doe
5 Stanly Jeff
6 Sarah John
With a single sql query, how will you cleanup the database (eliminate redundant data from above table)
Which data structure will you use for creating a real world dictionary?
You have a sorted circular linked list and a sorted linear linked list. Write a program to merge these two arrays and create a new sorted circular linked list
You have 8 coins. 3 of them weigh x units, 3 y units, 1 a units and 1 b units. They are all mixed and look identical. You have to find the lightest coin in minimum number of weighing .
You are blindfolded and 20 coins are placed on the table in front of you. Out of them 10 coins have heads facing up and other tails. You are allowed to flip and move the coins. You should divide those coins into two sets such that one set contains 10 heads and other tails. You are allowed to only move or flip the coins
Delete the nth node in a linked list by passing only "n" as a parameter to the function. i.e the function does not have the address of the first node of the Linked list.
Determine the sequence of input which can be given in order to get a AVL tree rooted at 9?
A. 20,10,5,9,6,8,2
B. 2,8,6,9,5,10,20
C. 6,9,5,10,20,8,2
D. 9,20,10,5,6,8,2
A C & D
C
A B & C
How to count the number of ones in the a number's representation. If the number is too large and how would you speeden up using parallel processing or any other technique?
Remove whitespace characters in a string, in place and with out shifting
Given a convex polygon with n vertices, find the farthest pair of vertices in O(n) time.
That you are given 4 identical tablets. Of which 2 are for cold and 2 for headache. 100mg each. All the tablets look the same. You have a patient and you have to provide him with the medicine. You must give him one tablet for cold and one for headache. But you do not know which one is for cold and which one for the headache. So how will you give it to him. If he has more than 100mg of a specific medicine he'll die.
Find the best way to cut a rod of length N units into smaller pieces such that we get maximum benefit. The prices for each smaller pieces of rod is given for cut of length from 1 to N.
Example
Length |1 2 3 4 5 6 7 8
-----------------------------------------
price |1 5 8 9 10 17 17 20
Find the longest Palindromic sub sequence of a given sequence, for example if the sequence is XAYBZBA then length of longest palindromic sub sequence is 5 and it is ABZBA
Image is represented by pixels.Rotate an NxN image matrix by 90 degrees,where each pixel is given by each element in an array.
The two nodes in BST are swapped.Correct the BST.
Copy a single link list where each node has a pointer randomly pointing to another node in the list.
Convert a binary search tree into doubly linked list in sorted order in place.
You are given a matrix multiplication function which takes two matrix and returns resultant matrix. I have a square matrix A. Write code to find A^n.
Hi,
Can any one tell me how to sort combination of int and float numbers,i am confused that how to use collection as different objects are involved
for example if i want to sort numbers 2,5.7,6.2.3
then what collection can i use??
You have one table with a single column having three values a,b and c.
Current snapshot of the table is
Table :- tblTest
Values :-
tblColumn
a
a
a
b
b
b
b
c
c
We need and output in SQL Server in the format:-
Acount BCount CCount
3 4 2
Do not use temporarytable/variables/multiple queries in a single query.
Values are restricted to be a, b and c only but the count may vary and output will change accordingly.
What is Serial ID corresponding to serialization?
When/why would you not use the final keyword?
What is volatile?
What lock does the thread acquire if you call a synchronized object/static method?
If you had to make a List immutable, would you extend List or ArrayList?
What are the cons of making every object Serializable?
Where/when would you use final?
What's the difference between a Hash Table & Hash Map? How would you handle a collision where key/hash are different, and visa-versa?
Given a BST and 2 numbers a,b, find the number of hops to reach from a to b.
Given a set of unsorted numbers without a range, find the median.
No sort operations should be used. Solution should be of the order n log n.
There are two very large arrays. Write a program to take their union in a Java Set in a time efficient way.
write a program to replace 0 with 5 in an array given??
There is alarm in a mobile and mobile is switched off when alarm is set. how to debug this situation? write all the scenarios u approach to debug this issue??
write test cases for browser lik firefox or chrome?
Write test cases for media player in mobile?? functional and non functional
Write possible test cases for Water Dispensers?? both functional and non functional
Given preorder traversal array of a BST, recontruct the BST.
Given API:
int Read4096(char* buf);
It reads data from a file and records the position so that the next time when it is called it read the next 4k chars (or the rest of the file, whichever is smaller) from the file.
The return is the number of chars read.
Todo: Use above API to Implement API
"int Read(char* buf, int n)" which reads any number of chars from the file.
virtual function and dynamic binding is okey, but what is the use of dynamic binding ? why we need it ? we can use "if ... else " conditions and functions pointers instead.
what is function pointers? what is use of it ?
what is pointers and why pointers are used ?
This is one of the interesting questions asked to my friend who had a telephonic with Microsoft recently:
Question: Imagine you have a device that is used to count the number of leaves in a tree. And it has an output screen which displays how many leaves are present in a tree, plus a start/stop button. Write as many test cases as possible and sort them under as different test buckets as possible.
How to find a place to insert new element effictively in a max heap implemented using tree and we dont know the index or no of element in tree.
Given a boolean matrix where 0 represent the blank and 1 represent the dot.So,dots form a image.Find the number of images.i.e.
You have to find the number of blocks having continuous 1s.
11000
01001
10011
00000
10101
here,it is 5 images.
Delete the tree completely.Tree need not be a binary tree.
Write clean code.
Given a1a2a3a4...anb1b2b3b4..bnc1c2c3..cn.
Convert this array to
a1b1c1a2b2c2...anbncn.
Given a Binary tree,find the level at which the tree is complete.Complete Binary tree-All leaves should be at same level and every internal node should have two children.
Asked to write both Recursive and iterative code.
What are references in C++? Why do you need them when you have pointers?
Given any five random points on a integer grid, prove that the mid-point of at least one pair lies on the grid.
You are given a graph-tree kind of Data structure such that it has no cylces( can also think of it as a n-ary tree). It is a undirected graph. You have to find out the node which, if taken as root, would result in making height of every node as min.( Or you can say it will be balanced)
Print first 'n' numbers of this series.
2, 3,4,5,6,8,9,10,12,15,16,18,20...(Note: Each number of this series has prime divisors as only 2, 3 or 5)
You are blindfolded and placed in front a table with two jars. One jar has 50 red balls and other has 50 blue balls. What should be your strategy so that you pick up the red ball with more than 50% probability.
write a program to search by name or phone number(mobile or PNT) in database(phonebook,directory..etc. ) for e.g query 'ry'
its should display the all possible name which contain these word or letters .arya,surya,Marya,tarry,marry....etc.
some for phone numbers.....
After creating Huffman tree, how to print the huffman code for each character which are the leaf nodes?
leaf nodes contain: character (ex:'a') and its frequency
other nodes contain: character '*' and sum of the frequency of the child nodes.
Design the Class diagram for vending machine for Tea & Coffee. This machine can generate the diff type of tea like Cardemom, Elichi, Ginger. Same way 3 type of coffee. The thing is when you make the tea or coffee user can add n number of flavors like sugar, honey or etc.
In your application, why is JAVA preferred over C++?
In your application, why database (story history) is used at client side and not on server side ?
how map is implemented? how insert and delete works?
Can we use "char *" in map as a key?(note that he is not asking stl::string )
difference between deque and vectors. where deque can be preferred over vector? how deque is insert element works?
Give the output of the following code:
#include<iostream>
using namespace std;
int main()
{
int a=10,b=2;
b=a+++a;
cout<<b<<" "<<a"\n";
return 0;
}How to replace the m to m+5th bit of an int32 number in java?
How to create a Fiveton pattern in Java. But the twist is that the interviewer expected to keep track of the 5 objects , and once and object is gced, we should decrement the count and be able to create a new 5th object.
Is it possible to find all permutations of given string in time O(n) ?
A table composed of N*M cells,each having a certain quantity of apples, is given. you start from the upper-left corner. At each step you can go down or right one cell.Design an algorithm to find the maximum number of apples you can collect ,if you are moving from upper-left corner to bottom-right corner.
Write the code to trace a sum in in BST from root node to leaf node(linked list implimentation) . Function takes 2 parameters,root node and the sum. If sum of elements (any root->leaf) equal to the required sum function returns 1 else it should return 0.
Write a code to compress a string-
ex aaabbccd compress it to a3b2c2d1 .
aabbcc to a2b2c2
char* functioncompress( char * a)
{
}
When one or many process try to access the queue and update it at same time, which IPC is used to avoid mutual exclusion..MUTEX or Semaphores
You are given a number of points on the XY-plane, [(x0,y0),(x1,y1),(x2,y2),...].
A point (xi,yi) is dominant to another point (xj,yj) iff xi>xj and yi>yj.
Calculate all pairs of points such that one dominates the other.
A time complexity less then O(n*n) was required.
what is the difference between IN , ANY and ALL in oracle?
can anyone explain with an example?
how to manage memory in linux kernel?
How to stop recursion stack as soon as we find a result.
e.g. in a Tree recurion where the Order of the algo is O(n) and suppose we find the result just after 4 calls, can we empty the recursion stack and stop the ececution right away...
int main()
{
int i=-1, j=2, k=0, m;
m = ++i && ++j || ++k;
printf ("%d %d %d %d", i,j,k,m);
return 0;
}
explain output : 0 2 1 1
in asp.net does the master page contains our page or our page contains the master page who is the father ???
write the test cases for a chess application.
write a running c program. When you compile the program another c program shud run and output of the 3rd command must be printed. give the UNIX xommands for the same.
Given N points in 3d space give the minimum number of points as the vertces of the figure and their coordinates which enclose the whole set of points within it.
to reverse the content of stack,by only using stack operations.
can it be better than n^2.
Given list A with 4 integers between 1 and 10, you should come up with list B with three integers such that all the values in list A can be obtained by adding 1 or more values in list B.
Example:
input: 2 4 6 7
output:1 2 4
Explanation:
2-2
4-4
6-2+4
7-1+2+4
Given a Circuit (with resistors), we need to calculate the total resistance. Input will be like AB-5ohm, BC-6ohm, BC-10ohm, BC-20 ohm, CD-5 ohm. BC has been repeated twice implying they are in parallel. "Write a program by implementing efficient data structure for storing and calculating the total resistance."
Function that will accept a string as the only parameter and returns a string that contains the number of characters in each word (including punctuations) of that string. separated by spaces
Eg. Input : "career cup."
Output: "6 4"
eg. Input: "Dark. Knight, Rises!"
Output : "5 7 6"
Suppose you are troubleshooting a bug in a Windows application deployed in the field to several hundred users on identical hardware/OS configurations, and has been stable until a recent upgrade was rolled out a week ago. Now some users are reporting that the app unexpectedly exits without warning or reporting an error when working in a particular area.
Describe how you would go about solving this problem.
What feedback, would you give the developers responsible for the app's design?
Write a program to find the longest increasing sub sequence of a given array
input a text and a pattern. The pattern can have *, say a*b, a**b, *ab... find whether the pattern matches the whole input text.
search an element in sorted 3D Array .(Sorted in all the 3 directions) .
best time complexity (less than O(n^2))
Given a series of numbers as the input, the last one as the result. Use the rest numbers to calculate the result,only +, -, *, / are allowed. The order of the input cannot be changed. If there is an equation, print it; or print "no equation". If more than one solution, any working equation is fine.
example:
input: 2, 3, 1, 4
output: 2+3-1 = 4.
Find a Pythagoras triplet from an array of integers
better than O(n^2log n)
Given an array of positive integers, and a number K. Find pairs(a,b) from the array such that a%b=K. % is the mod(remainder) operation. The interviewer wanted better than O(n^2) time complexity.
Create the n-ary tree from the ancestor matrix.
matrix[i][j]=1 if i is the ancestor of j.
My answer-
find the root (row with all zeroes).
Set the column with a[i][root] =0
find all the rows with all zeroes.insert into the tree all the children.and push all into the queue.
pop and find the children ,insert into the tree with popped node as parent and push into the queue.
Can not implement properly as it needed some modifications.
This is asked from my friend at amazon bangalore.
Hey guys,
I am taking the microsoft online test next week. I think this is the first that microsoft is conducting prelims online. Can some one suggest what should i learn to do well in the test.
Hey guys,
I am taking the microsoft online test next week. I think this is the first that microsoft is conducting prelims online. Can some one suggest what should i learn to do well in the test.
Given a pointer to the root of a binary tree , check whether the tree is
balanced or not.
Dynamic programming problem: Coin change problem: Find the minimum number of coins required to make change for a given sum (given unlimited cumber of N different denominations coin)
Written round question for Epic systems. They asked two dynamic programming problems.
Write a dynamic programming solution for finding maximum contiguous sub-sequence sum.
Select the option that denotes, "runtime is proportional to five times the input size".
O(n5)
5O(n)
5*O(n)
O(5n)
largest subarray with equal number of 0's & 1's
given two numbers m,n return the first number r divisible by both....
Question Number 1
Consider a table "Student" consisting of columns (Student ID, Student Address, Course).
Every student is allowed to enroll in multiple courses and every course is allowed to enroll more than one student. Also every time a student changes address, all his relevant records must be changed to reflect the new address.
What would be the Normal form required to avoid this redundancy?
2nd NF
4th NF
3rd NF
1st NF
There is a Command line program which gives the length of the Triangle sides.
Now write the possible test cases to trace if the triangle is Scalene , Isosceles or Equilateral ?
What is the result for the following Unix Command?
> CD \a\b\d\.\g\.\..\..\..\c\..
After telling the answere.
Now write a program to handle this case?
Given pointers to the first node of two linked lists A and B which may
be merged at a point. The problem is to find the merge point if it exists
else return null.
file 1:
int arr[10];
file 2:
extern int *arr;
foo(){
arr[0]=10;
}
what can be the problems and in what conditions ?
Input:
3
3 1 2
nny
nnn
ynn
output:
2 1 3
n size of permutation P.First line of input is n.Second line is the permutation P.A Permutation X is said to be lexicographically smaller than Y if for all digits till i X[i]=Y[i] and for i+1 X[i]<=Y[i]so you can exchange the integers in the given permutation P if character j of line i+2 is 'y' then i th and j th integer in P can be exchanged .
Output:Lexicographically smallest premutation of the given P using rule
given a string . find the first unique character .
time complexity : O(logn) , space O(1)
Given an array of positive integers, print out all the numbers which are repeated an even
number of times? Can you do this without using additional storage?
how do u use persistent storage on browsers . what are various options .
my ans : html5 : we can use localstorage and persistent storage.
non-html5 browsers : we can use cookies .
how do u detect useragent in css . suppose u want to use different css on mobile devices.
my ans : media tag.
how do u authenticate and perform authorization if your server is stateless in java . how does entire process work . please explain detailed architecture for it.
Suppose you have 4gb list of integers on disk . you need to find kth largest element . how will you do that . sorting is not an option .
i had suggested that I would use 2 stacks to maintain k largest elements (eg. k=10 , then stack will store top10 numbers encountered so far ) . interviewer mentioned can we use array instead . please let me know what is the optimal way .
When singleton wont work as singleton??
What is a weakHashMap??weak References??
xplain with example
What is a Executer in threads??
How would you build a stock ticker service?
Assuming a preexisting list of 100 words, how would you efficiently see if a word received from input is an anagram of any of the 100 words?
What are some ways of improving performance of the web pages using HTML, JS and CSS optimization?
A list contains repeated numbers , all the numbers are repeated odd number of times except one which is repeated even number of time. WAP to find out that number ( which is repeated even number of times).
( I gave the solution using extra space . He then asked me to give solution without extra space )
Calculate circumference of a tree going clockwise and anticlockwise?
How will you perform the preorder and inorder traversal of binary trees without using recursion. Basically he asked first to write a method to perform iterative preorder tree traversal and then iterative inorder tree traversal.
Write a program
Given an array of N integers . Find the maxproduct of 3 numbers ?
When trying to send a SMS from a mobile if it fails? How do you debug or troubleshoot this problem?
Write a test plan for "Add to Cart " feature in a web application ?
Can we access the node of a tree using pointer ?
if yes then give an example to traverse tree using pointer?
We have 'm' people .Each person is given a list of people whom he
dislikes. Find the minimum number of homes such that all the people
are accomodated and in each house no person must dislike any other
person.
Tokenize the given string.
node* strtok(char* input ,char* delims)
Put the words seperated into the linked list and return the linked list.delims can be a single character or group of characters like "abc".
Dictate the code as you write.
Design GMail's "consider adding" feature when writing an email. Assume you already have 1M emails of some user 'X'.
More explanation: When you write email in GMail and add a email to 'To:', you will get a option saying "Consider adding: alice, bob, john....". He asked me to design this feature.
You are given a large set of integer numbers, ie. millions of numbers, you need t find out the number of times a number occurs in that array using hash table. WAP for that.
Given a BST, convert that BST into a doubly link list without using any extra space and that should be a sorted doubly link list.
you have array of characters with some spaces.. best way to take out only words..
input ==> a,a,b, , , c, , ,d,e
output ==> aabcde -- all spaces are removed..
best way to do?
Given a binary tree , find the sum of all the nodes , which are at a particular level from all of its existing leaves. ( note:- it might be possible a single such node would exist for two different leaf , in that case we need to sum it up only once )
Singly LL with value as character. Please find out the word formed by character LL is palindrome or not.
Time Complexity <n^2
Space Complexity O(1)
How will you return
intand
charfrom a function in C?
Implement LRU cache?
How would you implement Singleton pattern in a multi-threaded environment?
A link list is given with two pointer, 1st is pointing to next node and another is random pointer. Random pointer is pointing to any node of LL. WAP to create a copy of LL, without changing original list and in O(n).
WAP to implement ftoa function.
In how many ways, 8 black and 8 white coins can be placed in 8x8 chess board.
write a function/procedure, it should detect and report all UN-USED FUNCTIONS (i.e functions are defined but not called) in a C++ class(i.e suppose you are developing a c++ editor for code compilation) -- MS bing
You are given a tree with N nodes. Every node in the tree has a given weight. Your goal is to divide the given tree in two trees by removing exactly one edge such that the difference of sum of weights in the new trees is minimum.
Input
First line contains integer T, the number of test cases. First line of each test case contains integer N, the number of nodes. Next line contains the N integers, weight of node 0, 1 .. N - 1. The next N - 1 line contain two space separated integers x and y, describing an edge, where x and y are 0 based indices for nodes in the tree.
Constraints
T <= 100, N <= 1000
Output
Output a single line for each test case, which contains the min absolute difference between the sum of the nodes of the two trees.
Example
Input:
2
3
8 7 8
1 0
2 1
9
5 5 4 1 8 8 3 5 2
1 0
2 0
3 1
4 1
5 3
6 0
7 5
8 1
Output:
7
13
Author: xyler
Date Added: 15-07-2012
Time Limit: 10 sec
Source Limit: 50000 Bytes
Languages: ADA, ASM, BASH, BF, C, C99 strict, CAML, CLOJ, CLPS, CPP 4.0.0-8, CPP 4.3.2, CS2, D, ERL, FORT, FS, GO, HASK, ICK, ICON, JAR, JAVA, JS, LISP clisp, LISP sbcl, LUA, NEM, NICE, PAS fpc, PAS gpc, PERL, PERL6, PHP, PIKE, PRLG, PYTH, PYTH 3.1.2, RUBY, SCALA, SCM guile, SCM qobi, ST, TCL, TEXT, WSPC
Two numbers are called friendly if they share a digit. For example 1239 and 9760 are friendly where as 1234 and 9876 are not. You are given N numbers and you have to calculate the count of pairs of numbers that are friendly.
Input
First line of input contains an integer T, the number of test cases. For each test case, the first line contains N, the number of integers given. The next N lines contain N integers.
Constraint
T <= 10, N <= 10 ** 4, Each given number is between 1 and 10 ** 18
Output
For each test case, print a line containing the count of pairs of number that are friendly.
Example
Input:
2
5
2837 2818 654 35 931
5
183 665 908 774 362
Output:
6
3
Author: xyler
Date Added: 15-07-2012
Time Limit: 1 sec
Source Limit: 50000 Bytes
Languages: ADA, ASM, BASH, BF, C, C99 strict, CAML, CLOJ, CLPS, CPP 4.0.0-8, CPP 4.3.2, CS2, D, ERL, FORT, FS, GO, HASK, ICK, ICON, JAR, JAVA, JS, LISP clisp, LISP sbcl, LUA, NEM, NICE, PAS fpc, PAS gpc, PERL, PERL6, PHP, PIKE, PRLG, PYTH, PYTH 3.1.2, RUBY, SCALA, SCM guile, SCM qobi, ST, TCL, TEXT, WSPC
WAP to reverse the bits in integer (inplace)!!!
e.g i/p: 1011 o/p 1101
WAP which print its source code as its output!!!:)
devise an algorithm to color the graph in such a way that no two adjacent vertices have same color.You have to color them with any of the two colors say red or green?what will the time and space complexity of the solution.
find a number a matrix a[m][n] where all the rows and columns are sorted non-decreasingly.What will be the complexity of the solution.
find the balance index of an array where balanced index i is defined as the one whose left sum is equal to the right sum of the index .
i.e
summation (1 to i-1) = summation (i+1 to length of an array) firdt I gave o(n2) solution , but then before i could give O(n) solution it was time up for me,
O(n) solution will be we have to loop through i = 1 to N and find if ( sum of array - sum of array (1 to i-1 ) = ( sum of array - sum of array (1 to i+1 ) the return i.
Your thoughts?
there are N people in a room one of them is a celebrity .At least one person knows other but all knows celebrity.Celebrity doesnt know any one.There is an api isKnown(a,b) which returns true if a knows b.y.
I gave the O(n2) answer.
But I think this can be done in O(n) .We have to compare call isKnown(a[i],a[i+1]) && iskNown(a[i+1],a[i]) returns true remove both frmo the array else remove that a[i] which return true, this will reduce the array to the celebrity. order will be O(n) then.Your thoughts ??
Print list ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'] in 3 columns.
Example output:
a e i
b f j
c g
d h
User inputs a series of numbers and terminates the series by a zero. Your program should find the first three maximum values in the series and exclude them from the series and compute the average of the remaining numbers. (excluding zero as well)
Ex - 3, 7, 12, 2, 25, 8, 9, 13, 10, 0
First three maximum numbers = 25, 13, 12
Average of the rest = (3 + 7 + 2 + 8 + 9 + 10) / 6 = 6.5
User inputs a sequence of digits. Every digit is a keystroke, that is equivalent to some character out of a sequence of characters. Digit zero and five mean NULL. The table is given below
0 - NULL
1 - v, t, f, r, q
2 - f, t, k
3 - w, z, b, g
4 - r, s
5 - NULL
6 - f, i, r
7 - p
8 - l, o
9 - p
Generate all possible character sequence for a given sequence of digits.
Ex - If the user input 9801, your program should generate
{plv, plt, plf, plr, plq, pov, pot, pof, por, poq} (not necessarily in this order).
This problem is somewhat similar to the SMS problem. It basically boils down to generating a cartesian product of the character sets corresponding to keys.
There is an interesting game named one person game. It is played via a m*n grids. There is an non-negative integer in each grid. At first your score is 0. You cannot enter a grid with integer 0. You can start and end the game at any grid you want (of course the number in the grid cannot be 0). At each step you can go up, down,left and right to the adjacent grid. The score you can get at last is the sum of the grids on your path. But you can enter each grid at most once.
The aim of the game is to get your score as high as possible.
Input:
The first line of input is an integer T the number of test cases. The first line of each test case is a single line containing 2 integers m and n which is the number of rows and columns of the grids. Each of next the m lines contains n space-separated integers D indicating the number in the correspoding grid
Output:
For each test case output an integer in a single line which is maximum score you can get at last.
Constraints:
T is less than 7.
D is less than 60001.
m and n are less than 8.
Sample Input:
4
1 1
5911
1 2
10832 0
1 1
0
4 1
0
8955
0
11493
Sample Output:
5911
10832
0
11493
A set of integer values are being received (1 per day). Store these values and at any given time, retrieve the min and max value over the last k days. What structures would you use for storing and retrieving ?
Given Preorder and postorder traversals of a tree. Device an algorithm to constuct a fully binary tree from these traversals.
How to find the path to a node of a non-binary tree? It's easy if it's a binary but here it's non-binary.
c
#include <iostream>
using namespace std;
class base{
public:
virtual void func(int i,int j=10)
{
cout<<"base func"<<endl;
}
};
class der:public base
{
public:
void func(int i,int j)
{
cout<<"der "<<j<<" func"<<endl;
}
};
int main()
{
der dd;
base *bb = new der();
bb->func(10);
dd.func(10,1);
}What is the output of this.
Remove duplicates from min-heap.
Given positive integers from 1 to n, find out the number of ways of selecting k numbers that
add up to n, where k itself can range from 1 to n.
Find the kth smallest element in an array. How can we do it without sorting the array.
Given a String, write a routine that converts the string to an long, without using the built in Java functions that would do this. Describe what (if any) limitations the code has. For example:
long StringToLong(String s)
{
/* code goes here to convert a string to a long */
}
void Test()
{
long i = StringToLong("123");
if (i == 123)
... success ...
else
... failure ...
}
Implement insert and delete in a tri-nary tree. Much like a binary-tree but with 3 child nodes for each parent instead of two -- with the left node being values < parent, the right node values > parent, and the middle node values == parent. For example, if I added the following nodes to the tree in this
Find all unique pairs of element in an array that sum to S. For ex. If array = {2,4,6,4,6} and S = 8 then answer is {(2,6), (4,4)}
Given a dictionary of words, two APIs
Is_word(string)
Is_prefix(string)
And a NxN matrix with each postion consisting of a character. If from any position (i,j) you can move
in any of the four directions, find out the all the valid words that can be formed in the matrix.
(looping is not allowed, i.e. for forming a word position if you start from (i,j) and move to (i-1,j) then
from this position you cannot go back to (i,j))
Given a newspaper and a set of ‘l’ words, give an efficient
algorithm to find the ‘l’ words in the newspaper.
Q1) Given that there are n players and each one of them has played exactly one game with every
other player. Also given is an API that tells whether player ‘a’ won or lost to player ‘b’, where ‘a’ and
‘b’ could be any of the players. Arrange the n players in a length n array such that player at position
‘i’ has won from player at ‘i+1’ and lost to player at ‘i-1’
Interested in linear time solution
PS: Its not a sorting problem. Please notice that problem is not asking for ranking in decreasing order..
Why ans is 2 for both
--
int main() {
int x = 1;
x=x++/++x;
printf("%d\n",x);
return 0;
}======and======
int main() {
int x = 1;
x=++x/x++;
printf("%d\n",x);
return 0;}
Implement the plusplus operator when we are getting the input as integer array = { 9,9,9,9 }.output will be {1,0,0,0,0}
Write a data structure to capture long datatype? That means this data structure will keep more them 1000 or million digits.
there are list of random numbers like
1,3,23,76,908,34,256,12,43,11,2,-10
given an input suppose:13
find the combination of the numbers which adds up to 13.like 1+12=13,23+(-10)=13..like that
write a program so that it'll find all the possible combination of a string avoiding palidromes
example:if the input is:"abcde"
output would be:"a","b","c","d","e","ab","ac","ad","ae","bc","bd","be","cd","ce","de","abc","abd","abe",...
but if you have already "abc",dont create"cba"
write a program so that the
input be a no suppose 5 it will give
output as
1+2*2+3*3*3+4*4*4*4+5*5*5*5*5
write test cases for digital pen?
write test cases for reverse string for ABC?
write test case for iphone weather app?
What is the main use of interface ? Provide a real time example that shows it
What is the importance of overriding in java ? Give any real life example . How is it increasing the code reusability and robustness .? Cant we create new function instead of override ? What difference will it make ?
How can I read a file in, compile, and execute it at run time?
How can I get a list of all symmetric key generators? How can I add one?
• Can you show me how to write a meta-class that will allow fixed named methods to be invoked before and after a method in an instance of that class is invoked?
What does it mean for two classes to have a different type erasure?
Given two strings .Print all the interleavings of the two strings.
Interleaving means that the if B comes after A .It should also come after A in the interleaved string.
ex-
AB and CD
ABCD
ACBD
ACDB
CABD
CADB
CDAB
An array arr[] has coins of several denominations. Given the array and a required Sum find the minimum number of picks to get that sum. eg:
Input: {1,3,10} Sum required = 11
Output: 1+10 => 2 pickings
Write a code in C for the following:
Starting from 1, assign an alphabet to each integer, for e.g. if input is 1 then A should be the output), 2 = B ....... 26 = Z. Similarly, 27 = AA, 28 = AB..........52 = AZ. 702 = ZZ, 703 = AAA and so on. The function takes only one integer argument . for e.g ConvertToAphabet(int x). One additional consideration here is, the user is free to provide any length of integer (bigint long int etc), no restriction there.
Example1:
const int a = 0;
int *ptr = const_cast<int *>(&a);
*ptr = *ptr + 10;
cout <<a<<" Address a "<<&a<<endl;
cout <<*ptr<<" Address in ptr "<<ptr<<endl;
&a and ptr contain the same but there values are different. can anyone tell how C++ interpret const_cast internally and why the value different and address is same of a and *ptr
Example2:
int a1 = 0;
int *ptr1 = &a1;
*ptr1 = *ptr1 + 10;
cout <<a1<<" Address a "<<&a1<<endl;
cout <<*ptr1<<" Address in ptr "<<ptr1<<endl;
in this example address and value are same.
Do the post order traversal of a binary search tree in iterative manner. You cannot use recursion. (Hint: You can use stack)
How to merge the 2 BST,
in 1) O(n)
in 2) O(log n)
?
Explain the output:
#include <stdio.h>
int main() {
int x = 1;
x=++x/x++;
printf("%d\n",x);
}
How to design three stacks using one array ?
Also,Is there any option by which you can delete questions submitted by you ? Please let me know.
Find the number of substrings of a string that are palindromes.
Find duplicates in Array. I presented solution in O(n) time and space using hash. Finally did it in O(n) time and constant space. Assumption: range of numbers is known.
Reverse a Linked List. Iterative and then recursive.
Reverse words : "I love to play" becomes "play to love I".
He wanted it to be done in place.
A 2d matrix is given filled with 1's and 0's. It is given that all 1's in a row come before all
the 0's. Design an algorithm for finding the maximum number of 1's in a row.
Given an array which contains the parent of the ith element in the n-ary tree.Parent[i] = -1 for root.
Find the height of the tree.
Gave O(n2) ,space O(1).
Expected Complexity- Linear
You can use extra space if you want.
Example-
{-1 0 1 6 6 0 0 2 7}
0 1 2 3 4 5 6 7 8
0 is the root here.
0 is the parent of 1 5 6
1 is parnt of 2
6 is parent of 3 4
2 is of 7 which is parent of 8.
Suppose there is a linked list ,how to find it is circular and also find the node where it becomes circular..like say
1->3->4->6->8->0
| |
7->23->5->9so here 4 is the head where circular linklist starts.
How can you copy the contents of an array A to contents of Array B without using loops and any standard string copy functions
Find preorder successor in BST.
What is the drawback for string type in Java . suppose you have to deal with millions of strings and u need to save them , how will you save them . imagine there is not enough space to save those strings . This is Big data related question . interviewer was just interested in knowing trick to save strings .
What would be the output of this program.
#define colums 4
#define rows 3
main()
{
int i,j,k;
int a[rows][colums]={4,5,6,7,8,9,10,11,12};
i=j=k=99;
for(i=0;i<rows;i++)
for(j=0;j<colums;j++)
if(a[k][j]<k)
k=a[i][j];
printf("%d\n",k);
}
write a pseudo code to calculate
func(n) = 2*(func(n-1)+func(n-2)) in log(n) complexity.
Given:.func(1) = 1;func(2) = 3
1.Explain Memory dumps in java
Design/implement a Hashset class of your own.
1.sort array {0,1,1,0,1,0,1,0,0,1,1,1,0} of binary numbers in O(n) time complexity using property of binary numbers.(no counting here)
1.Design one/two player tic-tac-toe,using Java.
1.Design a vending machine in java.takes coins of 2,3,7 ,using JAVA
Explain the output :
#include<stdio.h>
int main()
{ double i=0;
i+=0.1;
i+=0.1;
i+=0.1;
i+=0.1;
i+=0.1;
i+=0.1;
i+=0.1;
if(i==0.7)
printf("Equal : i=0.7\n");
i+=0.1;
if(i==0.8) printf("Equal : i=0.8\n");
else printf("Not Equal : i=0.8\n");
return 0;
}
Which of the following are Undefined Behavior ?
1. a[i]=i++;
2. printf("%d\n",(INT_MAX+1)<0);
3. 1<<32;
4. int arr[5];
return (&a[5]<&a[4]);
5. int arr[5];
return (&a[5]<&a[6]);
6. i=(++i,i++,i);
Yoda speaks in a jumbled language. Say " Newyork must go we to now". FInd the minimum number of swaps to convert this to proper sentence say "we must go to newyork now". This is similar to minimum swaps to convert string A to string B. where A, B are permutation of each other? Is there a decisive method? I tried using merge sort and selection sort and both time the answers varied.
Write a function to count the number of numbers between two 64 bit numbers a, b that have the sum of their bits equal to a fibonacci number. E.g Between 15 and 17 there are two numbers that have sum of bits equal to a fibonacci number.
15: 1111 sum=4
16: 10000 sum=1 (fibonacci)
17:10001 sum=2 (fibonacci)
I can do it with 0(n) where n being the no of elements between range but i want a better solution where i donot need to go through all the numbers. I want to know the pattern. Like if i take the complete range of 64 bit numbers then a simple pattern to identify all these numbers is (64c1+ 64c2+ 64c3+ 64c5+ 64c8.... 64c53). Similarly a pattern for given range.
Let's say there is a file consists of billions of records data.
The file cannot fit into memory, and you need to reverse each word in that huge file and then save the reversed words to another file.
How would you implement this?
char *p="havfun" , *q ="havfun" ;
are these two pointers equal ? If yes , then explain .
Compare the behavior of both the programs :
(1) . #include<stdio.h>
int main()
{
int i,a[3];
for(i=0;i<=3;i++)
a[i]=1;
for(i=0;i<=3;i++)
printf("%d\n",a[i]);
return 0;
}
(2) . #include<stdio.h>
int main()
{
int i,a[3];
for(i=0;i<=3;i++)
a[i]=i;
for(i=0;i<=3;i++)
printf("%d\n",a[i]);
return 0;
}
Is there no null character after "abcd" string in the following declaration .
char *p="abcd";
Explain the output :
int main()
{
struct{int a:1;
int b;
}obj;
obj.b=6;
obj.a=1;
printf("%d %d",obj.b,obj.a);
return 0;
}
In the following declaration ptr is
far * near * huge * ptr;
1. far
2. huge
3. near
4. all of the above
Given an array of size N, say A[N], count the number of pairs such that for i<j A[i]>A[j]. The interviewer was expecting for a linear complexity algo.
Given a binary tree whose node structures have an extra member to hold an integer value. Fill these with values that is equal to the total number of Left nodes in the left sub-tree minus total number of nodes in right sub tree.
Write pseudo code for Optimal game stratagy:
You have X amount with you, and 2N cards (N - winning cards, and N-loosing cards).
you have to play all the cards.
all cards are well shuffled, and one card is drawn randomly for each time.
if you pic one card means, next time you have to take one card from rest of the cards, i.e at last of the game you will left with one card.
If you bet 100 rupees,
If you got winning card ===> then you will get 200 rupees,
If you got a loosing card ====> then you will loose all your betting amount.i.e 100 rupees in this case.
You need to play all the cards. (I solved it.)
He asked me to solve it, with card replacement, i.e every time one card is drawn from 2N CARDS.
By using core dump file, how do you traverse a linked list.
i.e you got a core dump file while printing the linked list with head pointer. suppose at node number 40000,
each node has an unique identification number(lets say id starts with 1 to 100000, i.e 1 lac nodes are there in the list), I want to see the node content with identification number 122.
You have only coredump file and sorce code file with you. You are working with core dump file now.
1.Design a vending machine in java.takes coins of 2,3,7,JAVA
2.Design one/two player tic-tac-toe,Java.
3.sort array {0,1,1,0,1,0,1,0,0,1,1,1,0} of binary numbers in O(n) time complexity using property of binary numbers.(no counting here)
4.Design/implement a Hashset class of your own.
5.Memory dumps in java
....................................................................................Write a pseudo code. The question aims to test both your programming and analytical skills. Your implementation will be tested for both time and space efficiency.
The input format is strictly followed. Your program will be evaluated for correctness against multiple inputs. Some inputs will be very large (> 100,000 nodes).
Problem Statement
You are in-charge of the office jukebox. You are determined to do a very good job and make your colleagues happy. You ask them to email you a list of music bands they like. The number of bands each colleague likes is limited to 10,000.
Input
All input will be given on stdin. Your input will be of the form,
1. The first line will be an integer stating the number of lines of input.
2. The input will only contain alphanumeric characters, colon, comma, underscore and space [A-Z, a-z, 0-9, _, , ], +.
3. The first word will be the name of your colleague, followed by a colon.
4. A comma separated list of that person’s favourite bands will follow the colon.
5. Every line will be terminated by a newline character (\n).
An example input would look like:
6
Anne: Metallica, The_Doors, Black_Sabbath
John: The_Beatles, The_Doors, Metallica, Pink_Floyd
Kathy: U2, Guns_n_Roses, Led_Zeppelin
Jamie: Radiohead
Ashok: Guns_n_Roses, U2, Pink_Floyd, The_Doors
Sara: Blink_182, Iron_Maiden, The_Doors
Problem
You decide to use your data to find the people most compatible with each other. Two people are compatible if they have at least 2 bands in common. The compatibility of two people is directly proportional to the number of bands they like in common.
For each person in the list, output the most compatible person(s). If there is more than one compatible person, separate the names with a comma. If a person has nobody compatible, output nothing. For our example input, the output will be,
Anne: John
John: Anne, Ashok
Kathy: Ashok
Jamie:
Ashok: John, Kathy
Sara:
There are stream of integers coming....you have to implement put(int i) & get() function...put(int i) add the integer & get() function returns first k min numbers. Have to implement optimized space & time complexity
int[] array = {3,-1,-2,2,2,3,2,-6,2,3,-8,0,2};
out put needed :
{3,2,2,3,2,2,3,0,2,-1,-2,-6,-8}
order is maintained and -ve numbers are sent to rightmost in order.Design a code with single iteration to do it.
travel the tree vertically like
2
3 4
5 6 7 8
output:5 3 2 6 7 4 8
int main(){
short int a, b, c, d, e, f;
scanf("%d %d",&a,&b);
scanf("%d %d",&e,&d);
c=a+b;f=d+e;
printf("%d %d",c,f);}
What does the above code output on giving inputs 10, 10, 10, 10? and why ?
main(){
union d{
unsigned int a:1;
unsigned int b:3;
unsigned c:2;};
union d aa;
aa.b=6;aa.c=2;aa.a=1;
printf("%d %d %d",aa.a,aa.b,aa.c);}
What does the above code output?
#include<stdio.h>
#include<conio.h>
int main()
{
int i;
i=5;
i=++i/i++;
printf("%d",i);
getch();
}
Explain the output .
Given an inorder of a tree....build a tree where root is always greater than its left & right child
n numbers (both +ve and -ve) are arranged in a circle. find the maximum sum of consecutive nos. Do this in O(n) time
E.g.: {8,-8,9,-9,10,-11,12}
max = 22 (12 + 8 - 8 + 9 - 9 + 10)
Write the code for mutex in c that is threadsafe
There is a stream of numbers and you need to find the maximum k numbers at any instant when minimum of k numbers have passed.
Prove that addition of consecutive odd numbers from 1 will result in number that is the square of the count of numbers added.
e.g. 1+3+5 = 9 here count is 3 and the sum is 3^2 = 9
Give a mathematical proof
Write a code to in place sort the strings of the type "s1d3b2m0" to "sdbm1320". Solution must be of O(n) without the use of extra space. At max one temp variable could be used.
Effect of synchronize keyword in static and non-static methods in java
There are 25 horses. A group of maximum 5 can only be made. You need to find the best three horses in minimum number of races
There are three people and they need to know the average of their salaries without knowing each other's salary. How will you do that?
Reverse a linked list
There are four couples on one side of the river. There is an island in between that can hold only two people at a time. There is a boat that can carry maximum of two people. You need to transfer all 8 of them to the other side of the river. Condition is that a wife can not stay in the absence of her husband if any other male is present. She can stay with other females but not with other males in the absence of her husband.
Design and code a heap memory manager
What is MVC model.
How is Java different from javascript.
Divide a trapezium in 4 equal parts
There are two person A with Lock L1 and B with Lock L2 and a messenger M two send the box from one end to another. How to send the box so that M can never open the box.
What is the difference between a programming and scripting language.
There is an ant in a cube placed at one corner and you need to find the shortest path to the diagonally opposite corner. The ant can not fly tht is obvious.
Questions on Unions and its initialization and its memory usage.
How to implement classes in C
There is a channel which can send and receive signals and there is a sender and receiver. Sender can only send and receiver can only receive the message. Design classes for all three with the restrictions.
Design a base class that is uncopyable(need to take care of the = operator)
Questions on virtual methods and inheritence and C++
A stream of bits is passing, at any instance tell whether it is divisible by 3 or not.
atoi() implementation.
There are coins of 25 10 5 and 1 Rs. You got to tell in how many ways you can make change for an amount X. A working code was required,
Find the first character in the given string that is non repeating --- O(n) solution expected
Delete a node in Lined List
Level Order traversal in BST
Print the path whose some is S
Depth of BST.
Considering all features in a notepad like insertion,deletion,searching etc . Which would be the best data structure to be used for a notepad and why ?
There is an unlimited stream of integer numbers . As soon as 500 comes in the stream stop and return all elements which came before 500 in an array. All elements should be stored at contigous memory location.
In C
How Can we move the output pointer some point back?
(say I want to print ABCD, but ABD is already printed now I have to print C in between B & D without deleting anything.)
int fun(char *a){
printf("%d\n",sizeof(a));
return 1; }
int main()
{
char a[20];
printf("%d\n",sizeof(fun(a)));
}
Explain the output.
file 1 : int a[80];
file 2 : extern int *a;
int main(){
a[12]=100;
printf("%d\n",a[12]); }
Both files are compiled together . It's showing runtime error .
Why not linker error ?
int main()
{
int val,x=3,y=2,z=1,q=4;
val=(x>y?(x<z?20:10&&y>x?50:100):(y<z?40:9||x>q?30:10));
printf("%d\n",val);
}
Explain the output .
sublist of a sorted (ascending order)link list is reversed...
correct it
1--->2--->3--->4--->8--->7--->6--->5--->9--->10--->NULL
The following C program segfaults of IA-64, but works fine on IA-32.
int main()
{
int* p;
p = (int*)malloc(sizeof(int));
*p = 10;
return 0;
}
Why does it happen so?
#include<stdio.h>
int main()
{
int a=10;
switch(a)
{
case '1':
printf("ONE\n");
break;
case '2':
printf("TWO\n");
break;
defa1ut: // There should be an error .
printf("NONE\n");
}
return 0;
}
Check the output .. and explain why is it not showing an error ?
The character 'a' to 'z' are encoded as 1 - 26. Given a string of digits, compute the number of valid decodings of the string. For example, both 'aa' and 'k' can be encoded as '11'. Hence num_valid_encodings('11') = 2.
Given an array, print combinations of the array elements such that it is printed only once and the order is not important between the elements. Eg. array = [a,b,c,d]
o/p should be "", a,b,c,d,ab,ac,ad,bc,bd,cd,abc,abd,acd,bcd, abcd.. so it should not repeat abc in the form cab or bca etc..
Output number wil always be 2^n and do this in O(1) space.
Explain the output
#include<stdio.h>
void f()
{
int a[12];
int i=0;
for(i=0;i<12;i++)
a[i]=1;
}
void g()
{
int b[12];
int i=0;
for(i=0;i<12;i++)
printf("%d\n",b[i]);
}
int main()
{
f();
g();
return 0;
}
You are given intervals in form of Interval(i)={a(i), b(i)} where a,b are start and end points on a straight line. Given an array of intervals, Can you determine whether any such pair exist such that Interval(i) is contained in Interval(j). I told them the O(n log(n)) approach. If we have to find how many such pairs exist is it possible to do it in time less than O(n^2)??
What if i also have to print all such pairs??
There are 1000 tokens numbered as 1001-2000. Two functions allocate and release the tokens and their signatures are as follows, write their implementation
int alloc_token() {
//returns token number
}
void free_token(int token) {
}What is address alignment?
struct xx {
char a;
int b;
};
printf("%d", sizeof(struct xx));what would be output of this printf statement? and what would it be if it is union?
Consider you have a grid of size m x n. There are stones placed randomly in some of the squares of this grid. Design a way to find out minimum rectangular area which covers all the stones in this grid.
A) Write a function that takes input as integer and converts it into a linked list where each node represents a digit of the input integer.
e.g. i/p : 123
expected result: [1] => [2] => [3] => [null]
(catch: don't forget to consider case of negatives like -433 etc.)
B) Write a function that takes input as two linked lists shown as above (which are basically integers represented in linked list format) and calculate sum.
Consider any social networking website like facebook etc.
Design an algorithm / function that calculates minimum degree of connection between given two users. Assume that you are have already written function that returns a list of friends of given user :
getFriends(username/id)[EDIT]
Sorry guys for the wrong choice of words and caused confusion. It is "minimum degree of separation" and not connection.
(I still think there isn't much different but quite sure it has already confused so many people...anyways... :) )
follow this link for explanation : http://en.wikipedia.org/wiki/Six_degrees_of_separation
Write a function that prints pairs for target sum.
e.g.
array : 1 2 3 4 5 target: 6
pairs: (1,5) and (2,4)
void printPairs (int *a[], int target)
Design a class for maze.
You have yesterday's and today's log files that contains ids of users who logged in on amazon's website (there could be million entries). Design and implement way to find out user ids who logged in on both days.
Write a function that checks a Sudoku solution for its correctness and returns true if correct, false if not.
Techniques to shuffle an array?
Why doesn't *p in printf statement print 10.
int main()
{
int *p,i=10;
p=&i;
printf("Enter the pointer\n");
scanf("%p",p);
printf("%u\t%d\t%u",p,*p,&i);
return 0;
}
Given an array of positive integers of 2*n elements, you need to divide the array in two equal halves such that the sum of two halves are closest(or the difference of the sum is least). For e.g
Array = {1,2,3,4,5,6,7,8,9,10}
The desired two halves will be :
{1,4,6,7,10} and {5,2,3,8,9}
Difference between two halves = |28 - 27 | = 1 which is least among all other combination's.
You can safely assume that sum of whole array < 10^6
WAP to delete all the nodes from given BST.
WAP to return numbered index if input is excel sheet column header name.
e.g
excel sheet column headers are A, B, C , D ... Z, AA, AB...AZ, BA,, etc
if Input is D , output should be 4
and for AA output should be 27
WAP to delete all the nodes from given BST.
WAP to return all anagrams from the array of strings.
Given an array which is alternatively sorted. Find an element in it.
e.g. 12,2,16,5,18,32,33,38
Given two integer unsorted arrays, your task is to compare the BST formed by both the arrays.
any o(n) solution???
Hi all,
can anyone tell some methods & related brief for sorting the strings lexicographically ,
i just have implemented using quick sort.....
i want to learn abt hashing nd TRIE......bt still nt able to get.....how to sort using these methods
reverse a string
"hello my name is" to be displayed as "is name my hello"
find the no. of time a particular word is occurring in a string?
eg. "Hello I am going to I with Hello am"?
3 black caps and 2 white caps
randomly 3 caps are chosen and A,B,C are made to wear
they are standing in que and A can see B nC , B can only see C and C cant see anyone
A is asked which cap are you wearing? Ans from A was he dont knw
B was asked which cap is he wearing? B answered I dont know
But when asked C , he gave the correct answer
The question was...which color cap was C wearing?
I took 10min to ans
overall there will be 5 rounds which includes 4 Tech + 1HR round. They asked me data structures , java , oops concepts and some basic questions in selenium automation
there are 2 jars 5 lit and 3 lit capacity
measure 4 lit using them
damn easy question.... hehe!...answered in jus 60secs
What is wrong with the below code?
#include <iostream>
#include <string.h>
using namespace std;
class A
{
char *p;
public:
A(const char* str)
{
p=new char[strlen(str)+1];
strcpy(p,str);
}
~A()
{
delete p;
}
};
int main()
{
A s("Object s");
A t=s;
s.~A();
A u("Object u");
u=s;
return 0;
}#include<stdio.h>
void main(){
int x,y,z;
x=y=z=1;
z=++x||++y&&++z;
printf("%d %d %d \n",x,y,z);
getch();
}
what is the output n explain the output!!!!
what will be the o/p of the following program:
main()
{
int ret;
ret=fork();
ret=fork();
ret=fork();
ret=fork();
if(!ret)
printf("one");
else
printf("two");
}Explain the time complexity of external merge sort where each array has N elements & there are exactly N arrays.
Give an example of times you’ve used thread safe code.
#include<stdio.h>
#if something == 0
int some=0;
#endif
int main(){
int thing = 0;
printf("%d %d\n", some ,thing);
}
Explain the output .
#include<stdio.h>
#include<string.h>
void f(int **c){
printf("%d",c[0][0]);
}
int main(){
int c[2][2]={1,2,3,4};
f(c);
return 0;
}
Explain the output and also remove the error if any .
Write a C program which counts 1, 2, 3... and so on, every second. On pressing Ctrl+C, the timer should pause and then pressing Ctrl+Z should resume the timer
write a C program which generates random numbers between 1-100 (inclusive) on mouse movements.
Given an unsorted array of size 5.
How many minimum comparisons are needed to find the median?
Write a function that receives three integer inputs for the lengths of the sides of a triangle and returns one of four values to determine the triangle type (1=scalene, 2=isosceles, 3=equilateral, 4=error). Generate test cases for the function assuming another developer coded the function
Implement a circular queue of integers of user-specified size using a simple array. Provide routines to initialize(), enqueue() and dequeue() the queue. Make it thread safe.
we have one magic number while we multiply that no. with 2,3,4,5 or 6 we will get the permutations of that number only. what is that number?
ex: take magic no. as 135 while we multiply 135 with 2 to 6 numbers we have to get either 531 or 351.
the number should be not 0.
What is the difference between the two declarations?
int p=*(int*)i;
int p=*(int*)&i;
There are M servers each have a sorted list of N numbers. (N is very Large)
find kth smallest element from all the lists.
operations on servers are costly....
given 3 arrays, array a, array b, array c.
find all pairs where a[i] + b[j] = c[k]
a, b , c are sorted.
void freeList( struct node *n )
{
while( n )
{????}
}
Which one of the following can replace the ???? for the function above torelease the memory allocated to a linked list?
Choice 1 n = n->next;
free( n );
Choice 2 struct node m = n;
n = n->next;
free( m );
Choice 3 struct node m = n;
free( n );
n = m->next;
Choice 4 free( n );
n = n->next;
Choice 5 struct node m = n;
free( m );
n = n->next;void *ptr;
myStruct myArray[10];
ptr = myArray;
Which of the following is the correct way to increment the variable "ptr"?
Choice 1 ptr = ptr + sizeof(myStruct);
Choice 2 ++(int*)ptr;
Choice 3 ptr = ptr + sizeof(myArray);
Choice 4 increment(ptr);
Choice 5 ptr = ptr + sizeof(ptr);
I have given a Long Sentence and some words(to be searched in the sentence), i have to find the smallest part of the sentence which contains all the words to be Searched in that Sentence and print that part.
I have tried it, 1. First get all locations(indexes) of all words from the given sentence. 2. then try to find smallest part from these indexes of words.
But i am having problem implementing 2nd part . So i want some advice for it or if you suggest any other algorithm which can make it fast.
Example: If i have a String > "Hello, my name is undefined. but your name is not undefined." and i have to search word [is, undefined] then the answer should be printed is: is undefined //which is taken from the sentence 1st and we can not print from second sentence as it is " is not undefined" because it is not shortest.
import java.util.*;
import java.io.*;
public class ShotestSubSegment2
{
static SearchStr[] search;
static String copystr;
public static void main(String s[])
{
try
{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String str = in.readLine();
copystr = str.substring(0).toLowerCase();
int k = Integer.parseInt(in.readLine());
search = new SearchStr[k];
for(int i=0;i<k;i++)
{
search[i] = new SearchStr(in.readLine().toLowerCase());
getIndicesOf(search[i]);
if(search[i].noOfElements()==0)
{
System.out.println("No Segments Found");
return;
}
}
searchSmallestPart();//Dont getting Idea Of this
}
catch(Exception x){}
}
public static void getIndicesOf(SearchStr searchS)
{
String searchStr = searchS.getName();
int startIndex = 0, searchStrLen=0;
int index;
searchStr = searchStr.toLowerCase();
searchStrLen = searchStr.length();
while ((index = copystr.indexOf(searchStr, startIndex)) > -1)
{
searchS.add(index);
startIndex = index + searchStrLen;
}
}}
Design an algorithm that, given a list of n elements in an array, finds all the elements that appear more than n/3 times in the list. The algorithm should run in linear time ( n >=0 )
You are expected to use comparisons and achieve linear time. No hashing/excessive space/ and don't use standard linear time deterministic selection algo
Given a linklist, which has elements as A->M->A->Z->O->N. place vowels in the front of the list. But non vowels order should be maintained as per given input order.
input : A->M->A->Z->O->N.
output : A->A->O->M->Z->N
Design any datastructure with three methods insert, delete and getRandom in a highly optimized way. The interviewer asked me to think of a combination of datastructures to design a new one. Insert can be designed anyway but for random and delete i need to get the position of specific element. He gave me a hint to think about the datastructure which takes minimum time for sorting.
Can we do 3 sum problem on unsorted array in time (n logn) ?
3 sum problem : given unsorted array you have to find 3 numbers such that their sum is zero.
design a data structure to send a snapshot of a chess board at any time in between the game
In a tournament with N teams, where in one team can play only one match per day, develop an algo which schedules the matches in the tournament.
Each team shall play with the other team once(same as designing the league matches of a Cricket tournament like IPL)
He also asked me to optimise on days
At the Kernel level, if you want to write a memory leak analyzer, how will you implement it?
Implement LRU cache.
I think this question is already there on careercup.
I answered with hashmap + minheap.
Access takes O(1) and inserting new element takes O(lg n).
Given a stack.
Can we find range of numbers in the stack ?
Range is Max value in stack - Min value in stack.
Q > How will we design the stack to get Range in O(1) ?
Ans > I answered this one saying we have max variable and min variable defined in the stack. Whenever we push any number into stack, we compare with the current max and update, if necessary. Same with min.
Q > Then, he asked me what happens when we pop ?
If the element to be popped is the max element, how do we find the second max to be the new max element.
Ans > This, i answered we maintain two different stacks inside a stack called maxStack and minStack for max and min elements. He asked me to code everything. I did.
Then, he asked me if there are duplicates in the stack, can we optimise our solution so that the max element doesn't get inserted into the maxStack more than once and still we get all the above functionalities in optimised way ?
Ans > I answered we maintain a map of integer and it count. When we push into the stack, if the element is already there in the stack, we increase its count and update the maxStack or minStack, if necessary. When we pop, we decrease the count. If count becomes 0, then we update the maxStack and minStack, if necessary.
I coded everything then.
You have a number written starting from 1 to infinitive. You are performing some iteration. In
1st iteration you are removing number at a gap of one , in second iteration you are removing
number at a gap of two in remaining list and so on.You are given a number you have to tell that
it will be remove after certain iteration or not.Also calculate the complexity of you algorithm and
improve it if you can.
[Citrix]
There is an external array of integers on which you can perform the following operations in O(1) time.
1. get(int i) - returns the value at the index 'i' in the external array.
2. reverse( int i, int j) - returns the reverse of the array between index positions i and j (including i and j).
example for reverse: consider an array {1,2,3,4,5}. reverse(0,2) will return {3,2,1,4,5} and reverse(1,4) will return {1,5,4,3,2}.
Write a code to sort the external array. Mention the time and space complexity for your code.
We have given start and end array which corresponds to start and end time of lecture which are to be scheduled in some classes. Find minimum no of classes required inn least time complexity.
Every number ending in a 3 has a multiple which consists only of ones. Eg. 3 has 111, 13
has 111111, etc. You have to write a C function which will take a number ending in 3 and
will print the multiple consisting of all ones. The data structure that you use should consist
only of primitive data types. Remember that the multiple may overflow a computers integer
range, your function should be able to handle this.
There are 'n' vertices and 0 edges of an undirected graph. What is the maximum number of
edges that you can draw such that the graph remains disconnected.
if infinite streams of 1's and 0's are coming, give an algorithm to compute the remainder of current number formed by them after dividing it by 5....you cannot store whole stream..
how can you implement an abstract class in c++ without using pure virtual functions....??
If i type some numbers in my cell, all phone numbers which have these typed nos in any order should appear, tell data structure for this.
eg:if i type 926 then
932678....
92678...
9777726....
should appear.
[EDIT]: It seems you have lot of confusion.
Let me clear it through another example
eg: i enter 321, then
o/p(if they r in book)
9344241..
972153....
a gold sheet is given to you and different kind of shapes are given (shapes are not regular), you have to cut those shapes from the gold sheet such that there is minimum scrap i.e. minimum wastage of gold sheet.
Is there any alternative in c++/c to pass array to a function by value apart from cloning so that no change is reflected?
Given a paragraph of text, write a program to find the first shortest sub-segment that contains each of the given k words at least once. A segment is said to be shorter than other if it contains less number of words.
Ignore characters other than [a-z][A-Z] in the text. Comparison between the strings should be case-insensitive.
If no sub-segment is found then the program should output “NO SUBSEGMENT FOUND”.
Input format :
First line of the input contains the text.
Next line contains k , the number of words given to be searched.
Each of the next k lines contains a word.
Output format :
Print first shortest sub-segment that contains given k words , ignore special characters, numbers.If no sub-segment is found it should return “NO SUBSEGMENT FOUND”
Sample Input :
This is a test. This is a programming test. This is a programming test in any language.
4
this
a
test
programming
Sample Output :
a programming test This
Explanation :
In this test case segment "a programming test. This" contains given four words. You have to print without special characters, numbers so output is "a programming test This". Another segment "This is a programming test." also contains given four words but have more number of words.
Constraint :
Total number of character in a paragraph will not be more than 200,000.
0 < k <= no. of words in paragraph.
0 < Each word length < 15
There are 9 identical Maples out of which 1 is heavy. find that maple.
In A binary tree has the following nodes, print the output in zig zag form of the Binary tree
1
2 3
4 5
6 7 8
expected output :
1, 3, 2, 4 , 5, 8, 7, 6
Expression: 5 + 3 * ( 6 - 4 ) solve the expression from left to write as well as solve the sub ex-expressions from left to right (without using BEDMAS), take the given expression as string input, and print the output....note in this expression a white space has been added on both operators and operands?
Example: Input : 5 + 3 * ( 6 - 4 )
output : 16
(if you use BEDMAS rule then you get the output : 11)
Today I attended Amazon interview for the position of Programmer Analyst at Chennai.....Here I've post it, some of the questions they asked,
1. write the code ofTwo large numbers ( their integer limits are very large which has not in the integers range) , so give the output of adding the two large numbers?
Example;
str1 ="1111111111111111111111111111111111111111"
str2 ="22222222222222222222222222222222222222222"
stmstr = "33333333333333333333333333333333333333333"
(it has 41 digits that i've counted)
Question 4: Maze Problem (Bonus)
Starting point is m[0][0], need to find a path go to m[9][9]. 0 means OK, 1 means cannot go there, boundary is 0 and 9, cannot go beyond boundary. Each step can be made horizontally or vertically for one more grid (diagonal
jump is not allowed).
Your program should print a series of grid coordinates that start from m[0][0]
and go to m[9][9]
Hint: No need to find the shortest path, only need to find one path that gets
you to desitination.
Question 3: Implement Base64 encoding API -
DESCRIPTION
Base64 processes input in 24bit chunks by converting each chunk into 4 bytes of output. It does so by splitting input into four 6bit groups and using these as indexes in the following substitution table -
const char base64_map[] =
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz"
"0123456789+/";
If an input is not a multiple of 3 bytes, it's padded with zeros. In this case the output bytes that consist entirely of the pad data are replaced with '='.
Example
An input of 0x00 0x45 0xF2 is equivalent to 00000000 01000101 11110010
bit sequence, which's then split into 000000 000100 010111 110010
and these are substituted to produce the following base64 encoding
'A' 'E' 'X' 'y'
Question 2: write a binary search function on a sorted ascending int array. return the index of the element.
eg:
int t[] = [1,3,5,7,9];
find index of 5.
3 hour coding test.
Question 1: Delete an item in a linked list
Given a set of data ranges (i.e. 2-7, 5-9, 10-20), write a function to determine if there is any overlap within the set. Write test cases. Which data structure would be best to represent the intervals.
A very interesting question. Still awaiting answer so posting again.
What does this method do?
Stuff is a object in java with two members someStuff and anotherStuff
public static Stuff doSomeStuff (Stuff s0, Stuff s1) {
Stuff someStuff = s1.getSomeStuff();
if(someStuff != null){
s1.setSomeStuff(doSomeStuff(null, someStuff));
}
if(s1.getAnotherStuff()==null){
s1.setAnotherStuff(s0);
return s1;
} else {
Stuff myStuff = doSomeStuff(s1,s1.getAnotherStuff());
s1.setAnotherStuff(s0);
return myStuff;
}
}Does it have any bugs or edge cases where it will not execute?
Describe the time complexity of the function and comment on its effectiveness.
Two trees are given. Write a function to check if both of these trees are isotropic. Isotropic trees are those, when flipping few of the child nodes of a tree make both the trees equal. For e.g
.......1......
...2.......3.
.........4...5
......1.......
...3.......2..
.4....5.......
both of these are isotropic. If we flip the node with value 2 and 3 in the second tree then both trees will be equal.
There's a function named BiasedRandom which returns '0' with probability 'P' and returns '1' with probability '(1-P)'.
So define a Random function which surely returns '0' and '1' both with probability 0.5 using the above mentioned function(BiasedRandom).
Note:
-The BiasedRandom function can be used any times in the Random function as you want.
-And on each call of BiasedFunction from the Random function returns '0' and '1' with same probability(say P and 1-P resp.) on single run.
There's an array of length N. For every element of array, say 'X' , find a element 'Y' in the same array such that,
1. Value of Y<Value of X
2. Position of Y<Position of X
3. Position of Y should be as large as possible.
Note: If there's no such element 'Y' fro particular 'X' return NULL. Also give algorithm with time complexity less than O(N*N).
Without using extra space place all zeroes to left and 1's to right from an array of Zero's and 1's as below
011001 ans. 000111
public class Zeros_ones_New {
/**
* @param args
*/
public static void main(String[] args) {
int[] arrZerosOnes = { 0,1,0,1,0,1,1 };
int len = arrZerosOnes.length;
int firstOne = -1;
int lastZero = len;
for (int i = 0; i < len; i++) {
if (arrZerosOnes[i] == 1) {
firstOne = i;
break;
}
}
for (int u = len - 1; u > -1; u--) {
if (arrZerosOnes[u] == 0) {
lastZero = u;
break;
}
}
if (firstOne > -1 && lastZero<len) {
while (firstOne<lastZero) {
for (int j = firstOne; j < lastZero; j++) {
if (((j + 1) <= lastZero) && (j == firstOne)
&& (arrZerosOnes[j + 1] == 0)) {
arrZerosOnes[j] = 0;
arrZerosOnes[j + 1] = 1;
firstOne++;
/*if ((j + 1) == lastZero) {
break;
}*/
} else if (((j + 1) <= lastZero) && (arrZerosOnes[j] == 1)
&& (arrZerosOnes[j + 1] == 0)) {
arrZerosOnes[j] = 0;
arrZerosOnes[j + 1] = 1;
if ((j + 1) == lastZero) {
lastZero--;
}
}
}
}
}
for (int t = 0; t < len; t++) {
System.out.print(arrZerosOnes[t]);
}
}
}How to check a whether a very big number n^n = k
How to most efficiently find duplicates/commons in two sorted arrays of integers. No extra space should be used. My answer as below
public class Duplicate {
//private HashSet<Integer> duplicates = new HashSet<Integer>();
/**
* @param args
*/
public static void main(String[] args) {
int a[] = {0,2,2,4,6,8,8,9,9,10};
int b[] = {0,3,3,4,8,8,10,12};
new Duplicate().mergeAndCheck(a, b);
}
private void mergeAndCheck(int[] arr1, int[] arr2){
int len1 = arr1.length;
int len2 = arr2.length;
int pointArr1 = 0;
int pointArr2 = 0;
while((pointArr1<len1)&&(pointArr2<len2)){
if(arr1[pointArr1]<=arr2[pointArr2]){
if((arr1[pointArr1]==arr2[pointArr2])){
if(pointArr1==0){
System.out.print(" "+arr1[pointArr1]);
}else if(arr1[pointArr1]!=arr1[pointArr1-1]){
System.out.print(" "+arr1[pointArr1]);
}
//duplicates.add(arr1[pointArr1]);
}
pointArr1++;
}else{
pointArr2++;
}
}
/*for(Integer iNT:duplicates){
//System.out.print(" "+iNT);
}*/
}
}Does it always happen that stack always grows downwards & heap grows upwards?
If its so, then how does OS keeps the heap area protected from the interference of the stack & vice-versa?
If its not, then what factors affect it? OS version ? Compiler? Anything else??
Given three strings , find how many ways can the third string be generated by combining susequences of first and second strings in any order.
combining eg:“abc” and “de” can yield adebc,abdce,abcde etc...
Extend the JavaScript Array object by adding a method that removes duplicates.
Write a multithreaded blocking version of Bounded Queue.
There are writers which fill up the queue, and then readers which empty the queue.
If q is full, writer should block. If Q is empty readers should block.
The Queue size is finite... (its bounded).
Maximize parallelism, minimize resource usage etc...
Give output for the following code
#include<stdio.h>
void main()
{
int i = 5;
printf("%d\n",i++ + ++i);
printf("%d\n",i++ + ++i + i++ + i++);
printf("%d\n",++i + i++ + ++i + i++);
}Please give the output with os and compiler u used with proper explanation. Getting unexpected answers..... help !!!
This is old question posed by senior student.
Program to create a game of SUDOKU.
Design packman game.
Design LRU cache data structure
Convert relative path to absolute path.
for example:
/windows/abs/../temp/new/.../the output should be:
/windows/tempDesign saveEmail(), retrieveEMail() for our email system
Design a file system for our operation system
How would you know whether web server is freezing or not(a lot of queries then it may get stuck)?
System that can have 10K requests in a second. We need to save only the number of queries in a table. After 5 year user may want to see 5 years old history. user may want to see monthly history, history per yer, or per minute, per second(zoom in, zoom out). How would you design database.
10 000 integer numbers in an array, Each number is 10 bit. Sort the array
Given n x m array. Print the array in clock wise.
Like:
First row of array,
Last Column
Last Row
First Column
How to print the outside frame of a binary tree.
1. the order is top to down, left to right, then down to top
2. print all leftest node and rightest nodes
3. print all leaf nodes
4. print all nodes which only have 1 leaf
100
50 150
24 57 130
12 30 60 132e.g:
the output should be
100, 50, 24, 12, 30, 57, 60, 130, 132, 150
How will you find out size of a variable without using sizeof ();
Can you implement a java application without Abstraction?
Major difference between Forward and sendRedirect apart from browser calls sendRedirect and container process forward request?
What is volatile variable?
What is the difference when ArrayList is synchronized and used with respect to vector is there any difference?
Focus point is both will be in synchronized state whats happens internally.
Where is address of function pointer stored.?
Given an array of positive and negative integers find the first subarray with zero sum? no 0's will be a part of the input array and handle all the edge cases
Q: print out all leaf node path with non recursive method
The structure of node is *NOT* binary tree, is just a normal tree.
// print out all leaf node path
// 12
// 4 8 22
//1 2 3 9 18 24the output is like:
12, 4, 1,
12, 4, 2,
12, 4, 3,
12, 4, 8, 9,
12, 4, 8, 22, 18,
12, 4, 8, 22, 24,
While developing a globally distributed web application
that needs to manage time records for system internals
and for end-user usage (e.g. what date/time do i have the appointment?)
what best practices would you implement?
Hints - Server time versus user time. Distributed servers. Several timezones. Daylight savings time etc.
Given some string lexical order and you don't know which language these characters. How to find find the order of the characters.
There are four people who want to cross a bridge; they all begin on the same side. You have 17 minutes to get them all across to the other side. It is night, and they have one flashlight. A maximum of two people can cross the bridge at one time. Any party that crosses, either one or two people, must have the flashlight with them. The flashlight must be walked back and forth; it cannot be thrown, for example. Person 1 takes 1 minute to cross the bridge, person 2 takes 2 minutes, person 3 takes 5 minutes, and person 4 takes 10 minutes. A pair must walk together at the rate of the slower person’s pace. For example, if person 1 and person 4 walk across first, 10 minutes have elapsed when they get to the other side of the bridge. If person 4 returns the flashlight, a total of 20 minutes have passed and you have failed the mission.
please giv a sol...
i was asked the following question and they need java solution for it.
Checkers is an ancient board game played by two players, traditionally called 'Black' and 'White'. It is played by turns on an 8x8 board, which has alternating black and white squares. All the pieces are placed on black squares only and move in a diagonal fashion, i.e., a piece cannot move vertically or horizontally, but only diagonally.
When it is a player's turn, he can either make a move or a sequence of jumps. A jump is defined as a diagonal move over exactly one piece of the opposing colour. The piece that has been jumped over is said to be captured, i.e., it is removed from the board. The players try to capture as many of the opponent's pieces as possible and the game ends when all the pieces of any one player are captured.
Checkers rule states that the white piece (A) has a choice of moving to his left, or jumping over the black piece. Since the intent of the game is to capture as many of the opponent's pieces as possible, White should choose 'A' to jump over the black piece. After jumping, 'A' reaches a square from which he can jump further, either left or right. The jump to the left is better because it allows White to make one more jump, unlike the jump to the right, which leads to no more jumps. The white piece (, in the figure, can only move and not jump. Thus, according to the figure, White can jump thrice in one turn, using 'A' or alternatively can move once using 'B'. Obviously, the better choice is jumping with A.
You have to write a program which, given a board configuration, calculates the maximum number of jumps possible in one turn, by any White piece. Given the board above, the program would output '3'.
Notes:
It is illegal to jump over a piece of your own colour.
A player's turn is complete when he makes either a move or a sequence of jumps.
A jump can land only on an empty square.
Input specification:
The input will consist of eight (8) lines of eight (8) characters each. The characters will be one of the set {B, W, ~, #}.
� B => Black piece
� W => White piece
� ~ => An empty black square
� # => White square. Note that a piece can never land on a white square
Output specification:
Your program has to output the maximum number of jumps that can be made by any of the white pieces. If white cannot make any jump at all, then your program must print the integer '0' (zero)
Sample Input and Output:
Input:
#B#~#B#~
B#B#B#B#
#~#~#~#~
~#B#~#~#
#~#W#~#~
~#~#~#~#
#W#W#W#~
W#W#W#W#
Output:
4
Input:
~#~#~#~#
#B#B#B#B
~#~#~#~#
#B#B#~#~
~#~#~#~#
#~#B#~#~
~#W#W#W#
#W#W#W#W
Output:
5
Given three strings and a very large file, how will you print all the sentences containing one or more of these strings ?
Given an undirected graph G having N (1<N<=1000) vertices and positive weights. Find the shortest path from vertex 1 to vertex N, or state that such path doesn't exist.
find a^b using optimal algorithm.... [ no use of inbuilt functions?
How to find consecutive elements such that they have maximum sum ??
-2 4 2 3 -12 5 9 -3 4
=> Max SUM = 15
index i =5 to 8
How to find 4 largest elements of an given array of length n. Best possible option ??
There is an infinite integer grid at which N people have their houses on. They decide to unite at a common meeting place, which is someone's house.
From any given cell, all 8 adjacent cells are reachable in 1 unit of time.
eg: (x,y) can be reached from (x-1,y+1) in a single unit of time.
Find a common meeting place which minimises the sum of the travel times of all the persons.
Write an efficient algo and C code to shuffle a pack of cards.. this one was a feedback process until we came up with one with no extra storage
In a X's and 0's game (i.e. TIC TAC TOE) if you write a program for this give a fast way to generate the moves by the computer. I mean this should be the fastest way possible.
A real life problem - A square picture is cut into 16 squares and they are shuffled. Write a program to rearrange the 16 squares to get the original big square.
what is the output
main(){
int x=10,y;
y=++x++;
printf("%d%d",x,y);
}
Will this piece of Java code work:
class T {
public static void main(String args[]){
Object myObject = new Object();
synchronized(myObject){
myObject = new Object();
} //end sync
}
}
How do you delare a constant in java..other that using final keyword..
example, how will you create a constant StringBuffer??? What does using final mean in this case - it doesn't make StringBuffer constant..
Why do we use volatile? it doesn't ensure atomicity?
How is volatile used for objects?
How do you synchronize an object across all instances (static synchronization)
Why are static inner class used in the design? Are they really needed?
Why is enum added to java? Everything that it does can be done by a class..
I said it groups all constants of the same type at one place, he said - we can add static final variable in the class to achieve this...
A cube of 1 cm edge. How many cubes are needed to construct a big cube of 1000 cm edge
1> Solid cube
2> Hollow cube
Estimate the number of auto's standing idle in any area in Bangalore.
Name any one microsoft product, you have been using and suggest 5 improvements in it alongwith priority assignments p1 -p5.
Why the output of following code is always 0.000000
main()
{
float a;
scanf("%f",&a);
printf("%f",(int)a);
}
Given a node of a BST, make it the node of a new BST i.e modify original BST in such a way that the given node becomes the root.
Print all combinations of a number N, as a sum of positive integers?
eg.
3 =
1 2
1 1 1
4=
3 1
2 2
1 1 2
1 1 1 1
what is the o/p of following along with justifying logic ?
#include<stdio.h>
main()
{
int i=0;
prrintf("%%%%");
}#define a (sizeof(array)/sizeof(array[0]))
int array[]={23,34,12,17,204,99,16};
int main()
{
int d;
for(d=-1;d<=(a-3);d++)
printf("%d",array[d+1]);
return 0;
}
Why the output is a blank screen ??
Given an array A[n] such that A[i+1] = A[i]+1 OR A[i]-1, and a number k, can you determine in most efficient way whether k is present in A[n] or not?
Let suppose student is some class.
what is difference between
class student * s;
s = new s();
and s= new s;
Explain the output :
#include<stdio.h>
#define power(a) #a
int main()
{
printf("%d",*power(432));
getch();
return 0;
}
Two strings are given to you like abhinav and navigate and you have to give output abhinavigate and all the characters are stored in linked list node. Input is a->b->h->i->n->a->v and n->a->v->i->g->a->t->e and output should be a->b->h->i->n->a->v->i->g->a->t->e.
Consider a university having a very big campus spread in acres of land. The university is undergoing computerization. All the departments (at-most 50) are to be connected to form the intranet of the university. You have to write a program, implementing Prims algorithm, which will suggest the network topology and also minimise the total length of cable for connecting all the departments. Input to the program will be names of all the departments and straight line distances between the departments (Only those pairs of departments between which cable can be laid will be given). Output of the program should be the minimum length of the cable required.
Input specifications
The first line will contain 2 natural numbers, N and M, separated by a blank space. N indicated the number of departments in the university and M indicates the number of pairs of departments where the cables can be laid. The following M lines will specify the distances between M pairs of departments as dept1 dept2 distance Where dept1 and dept2 are names of the departments (maximum 20 characters) and distance is a positive integer (>0). Assume that the given distances between each pairs of departments will be unique and these M lines will contain atleast one pair for each department.
Output specifications
The first line of the output will be names of the departments as they are included in the solution separated by blank space. If two or more departments are included at a time then their names should be printed in the alphabetic order. The next line will be the minimum length of cable required to form the intranet, terminated with a new line character.
Sample Input/Output
input
7 10
physics chemistry 8
biology physics 9
biology office 15
chemistry office 4
chemistry sanskrit 5
sanskrit office 7
english office 16
english sanskrit 19
english cs 12
sanskrit cs 6
output
chemistry office sanskrit cs
physics biology english
44
Design a system of film ticket .There are many lots of factors that influence ticket price.Design a system that can adapt to the changes of ticket price.Just give its class diagrams.
This is my design,and who can give me some goog suggestions?
Ticket(Basic Clsass)
|
FilmTicket(Father Class)-->CalPrice(Basic Interface) | | | |
2DFilmTicket 3DFilmTicket CalCommonPrice CalVIPPrice
Write code to compute number of structural different binary trees for given 'n' number of nodes. (with and without Catalan number)
What does this method do?
Stuff is a object in java with two members someStuff and anotherStuff
public static Stuff doSomeStuff (Stuff s0, Stuff s1) {
Stuff someStuff = s1.getSomeStuff();
if(someStuff != null){
s1.setSomeStuff(doSomeStuff(null, someStuff));
}
if(s1.getAnotherStuff()==null){
s1.setAnotherStuff(s0);
return s1;
} else {
Stuff myStuff = doSomeStuff(s1,s1.getAnotherStuff());
s1.setAnotherStuff(s0);
return myStuff;
}
}What does this method do? Does it have any bugs or edge cases where it will not execute?
Describe the time complexity of the function and comment on its effectiveness.
how many sockets can you have?
what will a server do after getting a request from a client?
multicast VS broadcast
implement a deque
write atoi() function
what is bus error? common causes of bus errors?
difference between preemptive and cooperative multithreading
pipe VS message queue
shared mmy VS mmy mapped file
implement a deque
find the 2nd largest # in int array
given a large array of int return the length of the longest increasing(non-necessarily-adjacent) sub-sequence
Given an n-ary tree (i.e. it can have max n children). One need to roll up the tree from leaves back to root such that the data of root will be the sum of root's data and sum of all its children data.
how do you get the average value from a large data stream?
I used long long for calculating the sum and int for counting the total number, then divide the sum by total number, if the total sum overflows, have a class present a very large integer.
given an string with space and an dictionary for all words in the string, how do you find words in the string?
I used prefix tree to store all the words in the dictionary, and query works in the prefix tree takes O(n) time.
find the 2nd largest number in an integer array, what do you return if the array has only 1 element?
Find the nth most frequent number in array
Here is a good one i recently came accorss.
Really appreciate if someone could help me code this in Java
Print elements of a n-ary tree(a tree which may have more than two elements per node) breadth first reverse starting with the last level
nodes and up. The code need to fit the following method and interface.
method name: void displayBFSReverse (Node head);
Where Node implements the interface:
interface Node {
public String getNodeData ();
public List<Node> getChildren ();
}
The Tree Structure is
34
/ | \
3 56 12
/ \ |
89 7 22
|
78reverse in BFS and return should return
78 22 7 89 12 56 3 34
Current using a single git repository
How would you handle problems such as this:
- Product A is released in October 2003 with a certain set of frameworks code.
- Product B is released in February 2004 with newer frameworks code. We fixed 12 or 22 bugs
that affected product B. 7 of these fixes apply to
Product A.
- Product C is released in April 2004 with yet newer frameworks code. We fixed 32 more bugs. 12
fixes apply to Product A and 17 apply to
Product B.
- This continues for years, with a new product every few months. It's currently 2012 so you can
see where this is going! We have a lot of fixes accumulated in the frameworks, but tracking which
fixes apply to which products, and then deploying them, is becoming a lot of work.
Here is a good one i recently came accorss.
Really appriciate if someone could help me code this in Java
The Tree Structure is
34
/ | \
3 56 12
/ \ |
89 7 22
|
78Print elements of a n-ary tree(a tree which may have more than two elements) breadth first reverse starting with the last level
nodes and up. The code need to fit the following method and interface.
method name: void displayBFSReverse (Node head);
Where Node implements the interface:
interface Node {
public String getNodeData ();
public List<Node> getChildren ();
}
The function should return:
78 22 7 89 12 56 3 34
I was given a very interesting question.
You are given two very large files each containing integers in each line followed by a line break.
Produce a file with integers that are common in both files.
Estimate the time complexity of your code block?
Any edge cases and Bottlenecks?
Assumptions?
How would you solve this.
I did a little research on this and saw that some people suggested using Radix Sort for this and trying to split on large file into subsets and then using radix sort.
Here is the link
http://stackoverflow.com/questions/6520954/produce-a-file-that-has-integers-common-to-two-large-files-containing-integers
Can someone help me write this function. I read a lot of theories a lot of places but I am really looking for a code, preferably java for this.
This is a simple implementation of the same. I got a clarification that numbers are integers but the files are large but on one disk only.
I am using an approach as In case the file is too big to fit into memory on one go, break it into parts or read n integers at a time.and then use hashmaps to look for integers.
Cpmplexity: If the partition size is p and the file size is m then and no of rows per partition in n then ----- O(m/p * n) or O(N).
import java.io.*;
import java.util.*;
import java.io.FileWriter;
public class FileRead{
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
File file1 = new File("C:\\Documents and Settings\\chaos\\Desktop\\input1.txt");
File file2 = new File("C:\\Documents and Settings\\chaos\\Desktop\\input2.txt");
try{
Map mymap = new HashMap();
Scanner scan1 = new Scanner(file1);
Scanner scan2 = new Scanner(file2);
while(scan1.hasNextLine( ))
{
int line = scan1.nextInt();
mymap.put(line,1);
}
while(scan2.hasNextLine())
{
int line = scan2.nextInt();
try{
int val = (Integer) mymap.get(line);
if(val==1)
try{
FileWriter f1 = new FileWriter("C:\\Documents and Settings\\chaos\\Desktop\\output.txt");
BufferedWriter out = new BufferedWriter(f1);
out.write(line);
System.out.println(line);
}catch (IOException e){}
}catch(NullPointerException e2){}
}
} catch(FileNotFoundException e){e.printStackTrace();}
}
}When you receive a crash dump for a process from a particular customer, Is it possible to know the line number of which function has caused the problem?
How do you identify which process has crashed in customer env, if there are multiple process crash at same time.
Implement cache library which can hold more data than main memory.
which data structure you use? and why? and its complexity?
Lunatic server solution got a project in which they have to make a intranet web campus.
so entry for software developer , company make this problem.
solution must be in java.
Consider a university having a very big campus spread in acres of land. The university is undergoing
computerization. All the departments (at-most 50) are to be connected to form the intranet of the university.
You have to write a program, implementing Prims algorithm, which will suggest the network topology and
also minimise the total length of cable for connecting all the departments. Input to the program will be
names of all the departments and straight line distances between the departments (Only those pairs of
departments between which cable can be laid will be given). Output of the program should be the minimum
length of the cable required.
Input specifications
The first line will contain 2 natural numbers, N and M, separated by a blank space. N indicated the number
of departments in the university and M indicates the number of pairs of departments where the cables can be
laid. The following M lines will specify the distances between M pairs of departments as
dept1 dept2 distance
Where dept1 and dept2 are names of the departments (maximum 20 characters) and distance is a positive
integer (>0). Assume that the given distances between each pairs of departments will be unique and these M
lines will contain atleast one pair for each department.
Output specifications
The first line of the output will be names of the departments as they are included in the solution separated by
blank space. If two or more departments are included at a time then their names should be printed in the
alphabetic order. The next line will be the minimum length of cable required to form the intranet, terminated
with a new line character.
Sample Input/Output
input
7 10
physics chemistry 8
biology physics 9
biology office 15
chemistry office 4
chemistry sanskrit 5
sanskrit office 7
english office 16
english sanskrit 19
english cs 12
sanskrit cs 6
output
chemistry office sanskrit cs physics biology english
44
Hint : a simple prim's algorithm is implemented.
lunatic server solution is monitoring the wrong file entry in the server.
so company made another a problem for it to monitor AVL tree violation.
The problem should be solved in java...
problem states that...
This problem requires you to monitor a tree for violation of the AVL balance criteria as the tree is being
constructed.
The input to the program consists of a sequence of numbers. As you read in each number, check where the
node is going to be inserted into the current tree. [At the start, the tree is empty.] If that insertion can cause
the balance of any of the nodes in the tree to go beyond what is allowed by the AVL criteria, DO NOT add
the number into the tree. Instead, print out the number into the standard output. Numbers which retain the
AVL property of the tree should be added to the tree at the appropriate place as per the method discussed in
class. Continue with the remaining numbers. Please note that you do not have to do any balancing of the
tree! The input is terminated by –1.
The output from the program consists of the numbers rejected by the program. At the end, you should also
print out the count of such numbers rejected.
Hint: It would help to keep the height of the left and right subtrees of each node along with the node. Also
note that the process of checking for violation and actually inserting are quite similar; in the former case you
do not update anything but do everything else. This observation can be used to write the code.
Sample Input/Output
Input
3 5 1 6 2 4 9 7 -1
Output
7 1
(This means rejected key(s) are: key 7, totally 1 rejected key)
on last interview lunatic server solution asked 3 questions. one of them was very easy. the problem states that...
Given a stream of text, your task is to create a formatted paragraph out of it. The paragraph should be left justified and each line of text in the formatted paragraph should not exceed a given length. Each line should contain maximum possible characters.
In addition to the input text, a set of words with their possible hyphen positions will also be given. The hyphenation makes it possible sometimes to add incomplete words at the end of line, if the completed words overflow the line length limit. To indicate that this particular word is incomplete, a hyphen (-) is added at the end of such broken words. Remaining part of this word is placed at the beginning of the next line. The specified line length limit must be observed including the trailing hyphen character if any.
The input text will contain alphabets, digits, punctuation marks and spaces. The only white space character used is a blank space, which is used to separate words. Each line in a formatted paragraph begins with a non-blank character. Even if the input text has words separated by many spaces, your output should separate them by only single space or a line break.
Notes:
The list of hyphenated words will not include any punctuation marks that may occur in the text to be formatted. You may assume that the punctuation marks will occur only at the end of each word (alpha-numeric characters). That is there will not be words like They'll or Sita's anywhere in the input.
The word length will never exceed the line length limit.
The input text can always be formatted using the given constraints.
No word, hyphenated or otherwise will exceed a length of 20 characters.
Input specification:
First line has an integer n denoting the number of hyphenated words.
Next n lines give each of the hyphenated word with possible hyphen break positions in the word by a hyphen itself. For example, "hyphenate" is given as "hy-phen-ate" and "formatting" is given as "for-mat-ting".
Next line will be an integer denoting the maximum number of characters per line in the formatted paragraph, i.e., the line length limit.
Last line contains the text to be formatted into a paragraph. The entire text will be terminated by a new line. The length of text will not exceed 256 characters.
Output specification:
The output should be a sequence of characters, which begin each line of the formatted paragraph followed by a single new line character. Thus, there will be those many non-white space characters as there are lines in the formatted paragraph.
Sample Input and Output:
Input:
4
con-cept
pro-gram-ming
ob-vi-ous
im-pos-si-ble
25
Most people find the concept of programming obvious, but the doing impossible.
Output:
Mcos
Note : Candidate can not get characters of indices, which are multiple of 24.
you have to make program in java with proper coding and follow the problem statement.
You have a library provided by the vendor. All you have is header files and library files.
Library contains the class Shape and there is whole hierarchy tree (i mean classes which derive from this base class).
Now you want to add some function "getArea" (not originally present in the class or any of its derived class) in the class "Shape" , you dont have the source code.
Using this library, you have written a lot of code. Now you have to make some changes so that, any object of Shape class (or its derived class) will be able to call this function.
With your strategy, you should be able to override the definition of this function in the derived class.
What would be the output for the following code fragment?
main()
{
int i=300;
char *ptr = &i;
*++ptr=2;
printf("%d",i);
}
What would be the output for the following code fragment?
void foo(int b[][3] );
main()
{
int a [3][3]= { { 1,2,3} , { 4,5,6},{7,8,9}};
foo(a);
printf("%d" , a[2][1]);
}
void foo( int b[][3])
{
++ b;
b[1][1] =9;
}
(a) 8
(b) 9
(c) 7
(d) None of the above
Differentiate the above declarations.
1. const char *a;
2. char* const a;
3. char const *a;
For each of the above, which operation below is legal and which is not?
*a='F'
a ="Hi"
What does the following represent?
void (*abc(int, void (*def)()))();
What does the following do:
void afunction(int *x)
{
x=new int;
*x=12;
}
int main()
{
int v=10;
afunction(&v);
cout<<v;
}
a) Outputs 12
b) Outputs 10
c) Outputs the address of v
Write a method to sort an array of strings so that all the anagrams are next to each other.
implement dir *
Construct a BST and do its zigzag traversal.
You are given a huge log file which holds the entry and exit time of each person entering and exiting the office on a given day
format of file:
entry time exit time
09:12:23 11:14:35
10:34:01 13:23:40
10:34:31 11:20:10
.
.upto N entries for a given day
Design a function which returns the total number of persons in the office at any given time. e.g input to function is 11:05:20.
The interviewer said he could call the function every second with input 11:05:20, 11:05:21,11:05:22, 11:05:23..........14:30:30
I really did not understand how to optimize the function.
Write a program to find the first unique element in the following array:
{'a', 'a', 'u', 'b'}
Write o/p of following program
Class A
{
public static void main(String[] s)
{
System.out.println("Hello");
}
public static void main()
{
System.out.println("Hello");
}
public static void main (int args[])
{
System.out.println("Hello");
}
}
Write a method to change the password of a valid user in the following database table. The method accepts 3 parameters userId, oldPassword, NewPassword:
......................................................
UserId Username Password
......................................................
.......................................................
The password should be changed only when the old password is valid.
Design a class for a digital watch - outline the methods, properties, and class hierarchy. UML diagram welcome but not required. Write some test cases to test the above methods outlined.
Write a function that counts the number of primes in the range [1-N]. Write test cases for this function.
Write a java program to explain life cycle of a thread.
Write a java function to access properties from ini file.
(contents of ini file will be like: "username=xyz")
Write a program to find the missing element in second array(Array2):
Array1:
5 15 2 20 30 40 8 1
Array2:
2 20 15 30 1 40 0 8
Write a java program to count number of words in a file.
Without using loops, write a function to print 1 to 500 in serial order.
Write a String Reverser (using Recursion) and write JUnit test for the reverse method.
Write a java program to count number of words in a file.
Without using loops, write a function to print 1 to 500 in serial order.
Write a String Reverser (using Recursion) and write JUnit test for the reverse method.
Your function takes input stream of numbers continuously in chunks. The stream could be very large, and you don't have the memory in disk to store it. While the input stream keep coming to your function, at some point there will be a sentinel number that will indicate the end of the stream. So when you encounter that sentinel number, you have to return a random number from the input stream you got. The random number selection should be that the probability for each number in stream should be equal for selection.
How do you get the current code pointer (eip) into the eax register?
What is the output of the following procedure
{
void foo() {
int* a = 0;
char* b = NULL;
printf("%x %x", a, b);
printf("%x %x", *a, b);
printf("%x %x");
}
}
Expand the following fragment of C code to make it more understandable
{char* c = *a ? *++*a : *++*b;}
Find the(two) nodes which are at maximum distance in a binary tree?
This is not finding the distance but the nodes which are farthest.
Lunatic server solutions asked this problem for fresher recruitment in india.
On monday we asked this problem for freshers.
there was a very easy problem.
problem states that...
You are required to write a program to do simple pattern matching, in a string. The string in which the pattern is to be found, henceforth referred to as Master String, can be composed of the following character sets:
a-z {any character in the range a to z}
A-Z {any character in the range A to Z}
0-9 {any digit in the range 0 to 9}
The pattern to be matched is also a string, henceforth referred to as Scan String. The Scan String can be composed of the above character sets, as well as two special characters, which are: '.' and '*'. The dot ('.') is to be interpreted as matching any one character from the above character sets and the star ('*') is interpreted as matching zero or more of the previously matched character. The Scan String may or may not contain the special characters.
A pattern is considered matched when the longest substring that satisfies the pattern is returned.
Input Specification
The first line of input contains the Master String.
The second line of input contains the Scan String.
Both Master String and Scan String will not be greater than 80 characters in length.
Output Specification
Your program must output the length of the longest substring matched. If there is no match, then the length of the matched substring is zero.
Input:
abcd23Abdaaaa4g9
.*Abd. { dot-star-A-b-d-dot }
Output:
10
Input:
aaadaaabbbb129cd
a.*d { a-dot-star-d }
Output:
16
Input:
0AbC1dEf2GhI3jKl4MnO5pQr6StU7vWx8Yz9
3JkL4 { 3-J-k-L-4 }
Output:
0
Input:
090m90mm90mmm90mm90m909
0m*9
Output:
5
Green Bricks asked this question for the post of project leader for their upcoming project.
project engineer has to be in java.
green bricks also offered attractive salary.
the problem was as follows:
Given a set of figures and a board (a 2D array), you are required to figure out if all the figures can be placed on the board such that no two figures overlap each other. A figure can be of any shape and is represented using a matrix of 0s and 1s. The 1s in the matrix indicate the solid part that makes the figure.
Note:
Overlapping of 0s of figure A with 1s and 0s of figure B is allowed.
The figures provided are to be fitted as is without any rotation.
There is only one figure per matrix.
The matrix describing the figure will not have any empty row or column.
Input specification:
The first line contains two integers M and N (0<=50 and 0<=50), the dimensions of the board. The board is empty at the start.
The second line contains an integer F (0<=F<=10), indicating the number of figures followed by F figures.
Each figure has two integers R and C, the dimensions of the matrix containing the figure followed by R lines containing C integers 0's or 1's separated by a space.
Output specification:
If all the given figures fit onto the board then print YES followed by the number of empty cells on the board, separated by a space. If all the pieces cannot be fitted on the board together then print NO.
Sample Input and Output:
Input:
4 4
3
1 1
1
4 3
0 0 1
1 1 1
0 0 1
0 1 1
4 3
1 1 1
1 0 0
1 1 1
1 0 0
Output:
YES 0
this was the sample input output case.
you have to make the program for this which should also work on the following test cases.
Test Case 1:
4 4
3
1 1
1
4 3
0 0 1
1 1 1
0 0 1
0 1 1
4 3
1 1 1
1 0 0
1 1 1
1 0 0
Test Case 2:
4 4
2
4 4
0 0 0 1
0 0 1 0
0 1 0 0
1 0 0 0
4 4
1 1 1 1
1 1 1 1
1 1 1 1
1 1 1 1
Test Case 3:
8 8
8
2 2
1 1
1 1
2 2
1 1
1 1
2 2
1 1
1 1
2 2
1 1
1 1
2 2
1 1
1 1
2 4
1 1 1 1
1 1 1 1
4 4
1 1 1 1
1 1 1 1
1 1 1 1
1 1 1 1
4 8
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
1 1 0 0 0 0 0 0
1 1 0 0 0 0 0 0
you have to figure out the answers.
regards,
john
How would you eliminate and print duplicate elements of an array of 5 billion 32-bit signed integers
Reverse K elements of a linked list.
Solved on 31st May.
It still has one bug, if the number of elements in a linked list are not a multiple of K, then it truncates the linked list at a multiple of K.
1->2->3->4->5->6 becomes
3->2->1->6->5->4 for K=3
Eg. if K=5 and number of elements is 12, it will reverse till 10 th element and then truncate it. so when the reversed list is printed, only 10 elemtns with every 5 revesed is shown, need to fix this.
package ThreadPkg;
import java.util.*;
class link
{
int data;
public link nextlink;
link(int d1)
{
data = d1;
}}
class List{
link head;
static int rev;
link revhead;
List(){
head = null;
Scanner scan1 = new Scanner(System.in);
rev = scan1.nextInt();
}
boolean isEmpty(link head)
{
return head==null;
}
void insert(int d1)
{
link templink = new link(d1);
templink.nextlink = head;
head = templink;
}
void printlist(){
link head1 = head;
while(!isEmpty(head1))
{
System.out.print(head1.data + " ");
head1 = head1.nextlink;
}
System.out.println();
}
void reverse()
{
boolean flag=true;
revhead = head;
link previous=revhead,temp=null,temp2=null;int i=1;
while(true)
{
i++;
for(int j=0;j<(2*rev-1);j++)
{
if(isEmpty(previous))
{
// previous=temp2;
break;
}
temp2=previous;
previous=previous.nextlink;
}
for(int k=0;k<rev;k++)
{
if(isEmpty(revhead))
{
return;
}
temp = revhead.nextlink;
revhead.nextlink = previous;
previous = revhead;
revhead = temp;
}
if(flag){
head=previous;
flag=false;
}
previous=temp;
}
}
}
class RevKLinkedList {
public static void main(String[] args) {
List list1 = new List();
list1.insert(10);
list1.insert(20);
list1.insert(30);
list1.insert(40);
list1.insert(50);
list1.insert(60);
list1.insert(70);
list1.insert(80);
list1.insert(90);
list1.insert(100);
list1.insert(110);
list1.insert(120);
list1.printlist();
list1.reverse();
list1.printlist();
}
}Given a matrix of size n x m filled with 0's and 1's
e.g.:
1 1 0 1 0
0 0 0 0 0
0 1 0 0 0
1 0 1 1 0
if the matrix has 1 at (i,j), fill the column j and row i with 1's
i.e., we get:
1 1 1 1 1
1 1 1 1 0
1 1 1 1 1
1 1 1 1 1
complexity: O(n*m) time and O(1) space
NOTE: you are not allowed to store anything except
'0' or '1' in the matrix entries
How to find popular cost of the books,
say book1 $10
book2 $20
book3 $40
book4 $50
book5 $10
book6 $20
We can use any algorithm to find the popular cost.
(i think most repeated cost)
A newly established university in New York has its campus located in a remote corner of the city. The university offers several courses and students are required to take a certain number of these courses. Each course publishes its schedule of lectures on a day-wise basis, i.e., it publishes the days of the week on which it holds lectures. Each course chooses exactly three days of the week for lectures. Travelling to the university is a nuisance and all the students who attend courses there, seek to minimise the number of days that they should have to travel. Given each course's schedule, you have to help the students decide on a combination of courses, such that they minimise the number of days that they have to travel to the university.
The university has strict attendance norms and it insists that students should attend all the lectures that their respective course offers.
Assume that the number of courses required will never be greater than the number of courses offered. In addition, there will be a unique combination of days, which allows the students to take the required number of courses and minimise travel.
Input specification:
First line will contain total number of courses (T) and the number of courses you are required to register (R) for.
The next T lines will each contain name of the course and those days on which the lectures for the course are held. The first word on each line is the name of the course and the rest of the words are three-letter words signifying the days of the week. E.g., "Physics MON WED FRI".
Output specification:
You should output the names of the days on which the student is required to go to the University to attend lectures. These should be printed on a single line in sorted order (SUN to SAT) with a single whitespace as a separator. Terminate the output with a newline.
Sample Input and Output:
Input:
6 3
Physics MON WED TUE
Chemistry TUE WED THU
Biology WED SAT THU
Economics MON FRI WED
English TUE WED FRI
History MON THU FRI
Output:
MON TUE WED FRI
Input:
6 2
Physics SUN TUE WED
Chemistry TUE WED THU
Biology THU WED FRI
Economics MON WED FRI
English THU TUE WED
History FRI MON THU
Output:
TUE WED THU
The second round interview: Implement a binary tree with the given interface, then discuss the implementation via remote desktop and phone.
/*
* An interface for an sorted binary tree.
*
* The interface provides methods for inserting values, checking if certain values are contained and iterating over the elements.
* Note: Implementing classes should provide an iterator that traverse the inserted object in the sorted order.
*/
public interface IBinTree<V extends Comparable<V>> extends Iterable<V> {
/*
* Insert an object into the binary tree. Note: The tree should be sorted, inserting the same object twice is allowed but the insert is expected to be stable.
*/
void insert(V obj);
/*
* Batch-insert multiple elements.
*/
void insert(Vector<V> vec);
/*
* Check if the object is already in the tree. Return true if it is, false otherwise.
*/
boolean contains(V obj);
}The first round: Phone interview + online coding:
You are given an array of n integers, each of which may be positive, negative or zero. Give an algorithm to identify the start and end index, i and j, of the interval whose elements form the maximal sum of all possible intervals. Assume j >=i
e.g. {1 3 -8 2 -1 10 -2 1} -> i=3 , j=5 – sum = 11
Example non-maximal sum intervals:
i=0, j=5 – sum = 7
i=2, j=4 – sum = -7
I know about the classic "Tortoise and Hair" algorithm to detect cycle in a LinkedList. What is a similar fast way (without using hashtables) for finding the node at which the cycle starts i.e. the node with 2 incoming edges and one outgoing edge? I got asked this during an interview and she did not bother to tell me the answer!
An application given to you, but you dont have any documents for that appln. You need to test that application... How will you do??
Also, if you analyze the appln and find the flow for it how will you ensure that the flow u found is the right one??
Given set of N integers (both +ve and -ve), find the continuous subset where the sum is maximum. Return the start and end indices.
Given random integers in N number of files , with each file having set of integers (count different in each set). To find if the sum of all these integers divisible by 8 or not ? Optimize your solution.
What is conditional compilation ? Please explain it with an example.
write a program that displays the its source code as its output.
create an array and remove all the duplicates in the array.no duplicates are allowed in the array.display the contents of the array finally after the duplicates are removed.
You have a list of coins of some denominations(d1<d2...<dk). You have unlimited supply of these coins. Find out the how can u make a sum S using minimum number of coins.
DP solution was required as he was not satisfied with greedy approach.
In this problem, you have to implement a variation of Insertion Sort as described below.
Suppose X is an array of N positive integers to be sorted. In this scheme, another array Y is used to store the
sorted integers. This array is to be viewed as a circular array, ie. index (N-1)+1 = index 0 and index 0-1 =
index N-1. The sorted integers get stored in a circular manner in Y, ie, it is possible that the index of the
smallest integer may be greater than the index of the largest integer.
Eg. 6 8 _ _ _ 1 2 4 5 is a view of the array Y sometime into the algorithm. ’_’ indicates unused locations of
the array. Smallest integer 1 is at index 5, largest integer 8 is at index 1. So the sorted array in Y is to be
generated by printing the contents from index 5 to 1, assuming the array wraps around at the end, ie. after
index 8, the next index is 0.
Assume that h holds the index of the smallest integer in Y and t holds the index of the largest integer in Y.
Initially,
1. h = t = 0
2. Y[0] = X[0] ie. the first integer in X[] is copied as the first integer in Y[].
3. All other elements in Y[] are initialised to a dummy value -1.
The rest of the integers in X[] are now inserted one by one into Y[] such that Y[] always contains a sorted
list of integers, with the smallest integer at index h and the largest at index t. This is done in the following
manner:
Let I be the next integer from X[] to be inserted into Y[]. Scan the array Y downwards from index h (with
wrap-around at the end) till index t and find out the place in Y[] where I has to fit in. If I fits in at either end
of the list, then insert it at the appropriate place in Y[]. Modify either t or h as appropriate to indicate the new
array structure; ie. either t is incremented or h is decremented (with wrap-around).
If I fits in somewhere in the middle of the list, then I should be inserted by shifting all the S smaller integers
one place to the left or by shifting all the L larger integers one place to the right, depending on the number of
integers to be shifted. That is, if S < L, the smaller integers should be shifted one place to the left and if S >=
L, the larger integers should be shifted one place to the right. Again either h or t should be modified
appropriately.
Example
Integers to be sorted X[]: 25 57 37 48 12 92 86 33
Contents of Y[] after inserting each integer from X[]:
Initially (t=0, h=0)
25 –1 –1 –1 –1 –1 –1 –1
57 fits in at end (t=1)
25 57 –1 –1 –1 –1 –1 –1
37 fits in middle, S=1, L=1, so shift 57 right. (t=2)
25 37 57 –1 –1 –1 –1 –1
48 fist in middle, S=2, L=1, So shift 57 right. (t=3)
25 37 48 57 –1 –1 –1 –1
12 fits in at beginning, circular property, (h=8, t=3)
25 37 48 57 –1 –1 –1 12
92 fits in at end (t=4).
25 37 48 57 92 –1 –1 12
86 fits in middle, S=5, L=1, so shift 92 right, (t=5).
25 37 48 57 86 92 –1 12
33 fits in middle, S=2, L=5, so shift 12, 25 left (h=7, t=5).
33 37 48 57 86 92 12 25
Input Specification
The input will consist of a single line containing an integer N followed by the N integers to be sorted. All
integers are positive and are separated by a single space. There will be no duplicates among the N integers.
Output Specification
The output should consist of N lines, each line containing N integers. The N integers are the contents of Y[]
(ie. Y[0] to Y[N-1]) after the insertion of each integer from X[]. All integers on a line should be separated by
a single space. N will be less than 50.
Sample Input/Output
Input
8 25 57 37 48 12 92 86 33
Output
25 -1 -1 -1 -1 -1 -1 -1
25 57 -1 -1 -1 -1 -1 -1
25 37 57 -1 -1 -1 -1 -1
25 37 48 57 -1 -1 -1 -1
25 37 48 57 -1 -1 -1 12
25 37 48 57 92 -1 -1 12
25 37 48 57 86 92 -1 12
33 37 48 57 86 92 12 25
Rain strikes and the roads are flooded, Mr X has to get home from work. Your task is to make sure he
returns home in the shortest time.
Consider the roads as a graph with crossings as nodes, and the path between two nodes as an edge. Assume
the graph is undirected and the nodes are numbered, 1 to V (V <= 50).
The input consists of :
1. An integer H on a line, this is the height of Mr X.
2. Two integers N and M on the next line, where, N is the number of edges in the graph. M is the
number of nodes in the graph.
3. A sequence of N lines each having 4 integers : C1 C2 T D where, C1, C2 are the nodes (or
crossings), T is the time it takes to go from C1 to C2. D is the water depth along the edge(or road)
from C1 to C2.
Note: The depth D has to be less than the height of Mr X for him to be able to take the road.
4. Two integers S and E indicating the node at which Mr X starts and where he is expected to go to,
respectively.
As output you have to give the shortest path starting at S, listing each vertex in the order and ending with E
that Mr X can take. Assume that there will be at least one way to reach the destination and that the shortest
path is unique.
Sample Input/Output
Input
5
10 7
1 2 10 4
1 4 6 3
1 5 8 2
2 3 2 1
3 7 1 2
2 6 1 3
4 6 4 4
6 7 2 5
5 4 2 6
5 7 6 1
1 7
Output
1 2 3 7
Consider a hash table of size N, numbered 0 to N-1. You have to insert integers into this table using the
hashing technique given below:
Let i be the integer to be inserted. Compute the index j of the location where the insertion is to be made as j
= i mod N. If this location is empty then put the element at this position else recompute the next location as
follows:
Remove the right most digit of i. Using the new value of i, recompute j = i mod N.
If the digit removed was odd, then move j locations forward from the current location else move j locations
backward from the current location (assume 0 as even). Note that this move will wrap around both the edges
of the table.
Keep doing this till you either find a free location or all the digits of i have been removed. When i comes to
only one digit, and its rightmost digit is removed, the number remaining is zero - therefore, this will lead to a
zero-step move.
If all digits of i have been removed and yet unable to find a free location, from the last location tried, start
moving in the direction corresponding to the last digit removed. Keep moving till you detect a free location.
Assume that the number of integers inserted is not more than the table size.
Input Specification
The first line will contain just one integer. This will give the table size, N. On the next line will be the list of
positive integers that need to be inserted into the table. The integers will be separated by a space each, and
the last integer will be -1 indicating end of input. (-1 is not to be inserted into the table).
Output Specification
The output should contain, for each integer, the locations that were checked while inserting that integer
(including the location in which the integer was finally inserted). The locations checked for each of the
integers should be output on a line by itself, separated by one space each, each line being terminated by a
new line.
Sample Input/Output
Input
7
38 52 145 16 179 4 -1
Output
3
3 5
5 5 4
2
4 0
4 4 3 2 1
On last sunday in the interview round this question was asked.
An older person has a very old computer at his house. It is so old that there is no notion of virtual memory in the operating system. Instead it uses a simple memory allocation technique called the 'Best Fit Algorithm'. The BFA works like this:
Whenever a request comes in for some memory space, the OS looks for the smallest, continuous empty space, which can satisfy it, and allocates a portion of this region to the program making the request. If such space cannot be found, the program is terminated and all the memory used by the program is freed. Any program can get terminated due to two reasons:
The program exits
Enough memory is not available to start the program or keep it running
All memory requests that come in at the same time-instant are processed in ascending order of process-id. If while processing, a program is terminated for lack of memory, all memory held by it is freed before processing any other request and no further memory requests by the terminated program are considered. All termination is also done in order of process-id.
You have to write a program to simulate this algorithm and print out the number of processes that were terminated due to lack of memory.
Note:
1.No process will request for memory before its start-time or after its end-time.
2.All memory sizes are specified in KB.
3.The memory is linear in nature, i.e., addresses do not wrap around. It starts at zero and goes up to N-1 KB.
4.At a given time unit, all processes that have reached end-time will be terminated (and memory freed) before other memory requests are serviced.
5.The total free space available in memory might be enough to satisfy a request, however the OS will terminate the process if a continuous region of empty space is not found
Input specification:
First line has an integer N (0 < N <= 1000), size of the memory in KB.
Second line of input will have integer P (0 <= P <= 20), the total number of processes to be run on the system.
Next P lines will have data for each process in the following format:
<process-id> <start-time> <end-time> <initial-memory>
These input lines will be sorted in ascending order of the process-id.Process-id will be unique integers greater than zero.
Next line will have integer R (0<= R <= 20), which specifies the subsequent memory requests by any process.
Next R lines have the following format:
<process-id> <request-time> <memory-required>
Output specification:
An integer specifying the number of processes that were terminated due to lack of memory
Sample Input and Output:
Input:
100
4
1 3 7 20
2 0 4 30
3 0 3 70
4 0 10 25
2
3 2 30
2 2 10
Output:
2
Input:
10
2
1 0 8 4
2 0 3 2
3
1 1 2
2 1 2
1 4 4
Output:
1
In 1000 wine bottles stack 10 are poisoned given 10 rats what is the minimum number of tries to find the poisoned one. Rat dies once it licks the poisoned wine.
You are given a string. You need to find the longest substring with unique characters in O(n) time
write a program for consumer and producer threads accessing shared queue, given primitives
CreateEvent
EnterCriticalSection/ EndCriticalSection
Sleep
Wait
SetEvent etc
A file contains set of anagram. print the output as list of similar word one by one.
e.g. plates stop staple pots meat not pot team
Output:-
1. Plates, staple
2. pots, stop .... etc
An older has a very old computer at his house. It is so old that there is no notion of virtual memory in the operating system. Instead it uses a simple memory allocation technique called the 'Best Fit Algorithm'. The BFA works like this:
Whenever a request comes in for some memory space, the OS looks for the smallest, continuous empty space, which can satisfy it, and allocates a portion of this region to the program making the request. If such space cannot be found, the program is terminated and all the memory used by the program is freed. Any program can get terminated due to two reasons:
The program exits
Enough memory is not available to start the program or keep it running
All memory requests that come in at the same time-instant are processed in ascending order of process-id. If while processing, a program is terminated for lack of memory, all memory held by it is freed before processing any other request and no further memory requests by the terminated program are considered. All termination is also done in order of process-id.
You have to write a program to simulate this algorithm and print out the number of processes that were terminated due to lack of memory.
Note:
1.No process will request for memory before its start-time or after its end-time.
2.All memory sizes are specified in KB.
3.The memory is linear in nature, i.e., addresses do not wrap around. It starts at zero and goes up to N-1 KB.
4.At a given time unit, all processes that have reached end-time will be terminated (and memory freed) before other memory requests are serviced.
5.The total free space available in memory might be enough to satisfy a request, however the OS will terminate the process if a continuous region of empty space is not found
Input specification:
First line has an integer N (0 < N <= 1000), size of the memory in KB.
Second line of input will have integer P (0 <= P <= 20), the total number of processes to be run on the system.
Next P lines will have data for each process in the following format:
<process-id> <start-time> <end-time> <initial-memory>
These input lines will be sorted in ascending order of the process-id.Process-id will be unique integers greater than zero.
Next line will have integer R (0<= R <= 20), which specifies the subsequent memory requests by any process.
Next R lines have the following format:
<process-id> <request-time> <memory-required>
Output specification:
An integer specifying the number of processes that were terminated due to lack of memory
Sample Input and Output:
Input:
100
4
1 3 7 20
2 0 4 30
3 0 3 70
4 0 10 25
2
3 2 30
2 2 10
Output:
2
Input:
10
2
1 0 8 4
2 0 3 2
3
1 1 2
2 1 2
1 4 4
Output:
1
With a linked list data structure, find if a given string is palindrome or not.
Explain singleton.
Given two arrays a1={1,2,3,4} and a2={5,6,7,8}, add the two array and return a new array n={6,9,1,2}
In javascript, what is the difference between "==" and "===" operator?
Write an algorithm to find the top 10 frequently occurring words in a book.
Given a 10GB file of integers and a RAM that can hold only 4GB values, how would you sort the integers in the file.
Given a binary tree print all the nodes that lie in a vertical line. So say the binary tree is root 11 -> left child 2 and right child is 15. 2 has left child 10 and right child 1 and 15 has left child 6 and right child 7.
The output will be
10
2
11,1,6
15
7
The tree is drawn in such a way that from a node, if a left and a right traversal is done, the node lies in the vertical line with the grand parent.
Given a m x n array that contains integers (positive and negative) find the rectangular sub array for which the sum of elements is maximum i.e. from all the sub arrays that can be formed from the given array, the sum of which sub array is the maximum.
The brute force method takes O(n^4), is there any better way to do this?
in this round the question was
java solution will be preferred.
programmar will get benefits.
Finding data on a huge hard disk has been a difficult task for computer manufacturers. In the constant quest to speed up the seek-time to find data, they've come up with a new algorithm. A simplistic view of a hard disk is as follows:
A hard disk consists of several platters, each of which has a head for reading and writing data. Each platter is divided into 80 tracks, numbered 1 to 80. Initially all the heads are on track 1. Once a head reaches a track, it can read all the data requests that have come in so far for that track, in one read-operation, which takes one unit of time. A head takes one unit time to move from one track to the neighbouring track. To minimize the seek-time, after every read operation, the head will move in the direction of the nearest pending request. That is, if the head was moving toward track 80 and while it was on track 5, two requests came, one each for track 2 and track 18. The head would continue to move in the same direction, read the data on track 18, re-evaluate the nearest track to be 2 and start moving toward track 2. If two competing requests for different tracks are equidistant from the head, then it will move in the direction of track 1. Initially the head of all platters is at rest. The head does not move if there are no requests for any track at the particular time.
The head on each platter follows this sequence during each time unit: -
1.All the requests for the current time unit are noted.
2.If there are any requests for the current track, read occurs in the same time unit.
3.If there were no reads, the head moves, if necessary.
4.Decides the direction of movement, if necessary.
You have to write a program to calculate the number of fulfilled requests per platter, after the specified time. If a particular platter has had no read-requests throughout the simulation, its count of fulfilled requests is '0'. The simulation starts at the beginning of time unit 1 and finishes at the end of time unit T
Input specification:
The first line of input will be an integer P (0
<= 20), signifying the number of platters.
The second line of input will be an integer T, specifying the time unit after which the output is to be printed.
The third line of input will be an integer N (0<=N<= 100), specifying the number of read requests that are coming in.
The next N lines will contain the read requests in the following format:
<time-of-request><space><platter-number><space><track-number>
Platter numbers start from 1 to P
All of the above will be integers separated by a single space.
Output specification:
Your program has to print N lines of output in ascending order of platter number in the following format:
<platter-number><hyphen><requests-fulfilled>
Sample Input and Output:
Input:
2
5
4
1 1 1
1 1 2
3 2 3
2 1 3
Output:
1-3
2-0
Input:
3
53
7
2 3 50
51 1 2
1 1 3
51 1 2
1 2 80
2 2 5
2 2 1
Output:
1-3
2-2
3-1
hi to all tech brains.
we made an interview round and ask this problem.
problem needs complete solution in java.
Any one of you who can solve it may appreciate and will get some benefits.
In this problem, you have to implement a sorting algorithm called Tournament sort, which uses a complete
binary tree.
The depth D of the tree will be given as input. Also, N positive integers will be given, where N is the Dth
power of 2 (ie, 2 ** D).
Construct a complete binary tree of depth D and fill in the leaf nodes with the N given integers in the order
given ie. the first integer should be at the leftmost leaf and the last integer should be at the rightmost leaf.
Next, update all the non-leaf nodes in the tree such that each nonleaf node contains the maximum of the
values in its children. Thus, the root will contain the maximum of all the N integers.
Implement a procedure ’maxdelete’ which essentially removes the maximum value from the tree and updates
the tree as follows:
1. traverse the tree from the root
2. find the leaf with the maximum value ie. the value at the root. (note that in this tree, if the value at a
non-leaf node is T, either its left child or its right child will have value T).
3. replace the value at that leaf node with -1 and
4. update the rest of the non-leaf nodes such that each non-leaf node contains the maximum of the
values in its children.
Perform the ’maxdelete’ operation 3 times on the tree and print out the INORDER traversal of the tree after
each operation.
Example
Given depth = 2
Given integers: 25 57 37 48
Constructed and updated tree:
57
/ \
57 48
/ \ / \
25 57 37 48
after first 'maxdelete'
48
/ \
25 48
/ \ / \
25 -1 37 48
after second 'maxdelete'
37
/ \
25 37
/ \ / \
25 -1 37 -1
after third 'maxdelete'
25
/ \
25 -1
/ \ / \
25 -1 -1 -1
Input Specification
The input will consist of a positive integer D followed by a positive integer N (where N is the Dth power of
2) followed by N positive integers. All the integers are separated by a single space and will be on a single
line. There will be no duplicates among the N integers. D will be greater than 1 and less than 9.
Output Specification
The output should consist of 3 lines. Each line should contain the INORDER traversal of the tree after a
’maxdelete’ operation. All the integers on a line should be separated by a single space.
Sample Input/Output
Input
2 4 25 57 37 48
Output
25 25 -1 48 37 48 48
25 25 -1 37 37 37 -1
25 25 -1 25 -1 -1 -1
int count = 0;
for(int i=0; i < 10; ++i)
count = count++;
std::cout << count;
what is the output for the above c++ code?
Definition of high-level operating system (HLOS).
In an unsorted array of first N natural numbers. The array contains a number which is dulicated and one is missing. Find both the numbers.
Given a circular table and a large no. of circular coins of same size. There are 2 persons playing a game of plotting coins on the table such that each person gets a chance to place the coin alternatively. The coins are to be placed flat on the table and they should not overlap. The person with more no. of coins on the table wins. Find a way (design an algorithm) in such a way that you always win the game. Would you go first or would you let your friend go first? Also each person is allowed to place to coin randomly anywhere on the table. In the end if there is space left to put 2 coins on the table and you put your coin in center. You win.
Consider a service counter. People waiting for service form a queue. At the start, the queue is empty and
time is 0. The service time per person is 3 minutes.
The input to the program consists of an integer N followed by a sequence of integers indicating the arrival
time (in minutes) of the customers. These times are given as offset from the start of the simulation, so that an
input of 44 means 44 minutes from the start of simulation. The sequence of input numbers is terminated by
the number -1.
Your program must simulate the queue and print out the following:
1. The number of customers waiting in the queue at time = N minutes from the start of simulation.
2. The arrival times of the customers in the queue at that time, in increasing order.
Each integer must be separated by a space. Terminate your output with a newline character.
For doing the computation, you can assume that if the counter is expected to be vacant at time t, the first
person in the queue will be scheduled for service, before the counting is done for time t.
You must use the queue data structure to solve this problem.
Sample Input/Output
Input
9 0 2 5 6 6 8 10 -1
Output
2 6 8
provide the solution using QUEUE.
This problem will tell you your coding power.
Reverse K elements of a linked list.
Solved on 31st May.
It still has one bug, if the number of elements in a linked list are not a multiple of K, then it truncates the linked list at a multiple of K.
Eg. if K=5 and number of elements is 12, it will reverse till 10 th element and then truncate it. so when the reversed list is printed, only 10 elemtns with ever 5 revesed is shown, need to fix this.
import java.util.*;
class link
{
int data;
public link nextlink;
link(int d1)
{
data = d1;
}}
class List{
link head;
static int rev;
link revhead;
List(){
head = null;
Scanner scan1 = new Scanner(System.in);
rev = scan1.nextInt();
}
boolean isEmpty(link head)
{
return head==null;
}
void insert(int d1)
{
link templink = new link(d1);
templink.nextlink = head;
head = templink;
}
void printlist(){
link head1 = head;
while(!isEmpty(head1))
{
System.out.print(head1.data + " ");
head1 = head1.nextlink;
}
System.out.println();
}
void reverse()
{
boolean flag=true;
revhead = head;
link previous=revhead,temp=null,temp2=null;int i=1;
while(true)
{
i++;
for(int j=0;j<(2*rev-1);j++)
{
if(isEmpty(previous))
{
// previous=temp2;
break;
}
temp2=previous;
previous=previous.nextlink;
}
for(int k=0;k<rev;k++)
{
if(isEmpty(revhead))
{
return;
}
temp = revhead.nextlink;
revhead.nextlink = previous;
previous = revhead;
revhead = temp;
}
if(flag){
head=previous;
flag=false;
}
previous=temp;
}
}
}
class RevKLinkedList {
public static void main(String[] args) {
List list1 = new List();
list1.insert(10);
list1.insert(20);
list1.insert(30);
list1.insert(40);
list1.insert(50);
list1.insert(60);
list1.insert(70);
list1.insert(80);
list1.insert(90);
list1.insert(100);
list1.insert(110);
list1.insert(120);
list1.printlist();
list1.reverse();
list1.printlist();
}
}write a program to take a no. as input and generate the output in the form of LED display.
eg. if input in 102 op
__ __
| | | __|
| |_ | |__
|
If you implement an interface compile asks you to provide implementation of those methods. But in case of object.clone() how come this is inverse? Means you have overridden clone() method but your class doesn't implements copyable. How compiles does this mapping to tell user that CloneNotSupported ??
What is difference between following interface and abstract class:
public interface MyInterface
{
public int get1();
public int get2();
public int get3();
}
public abstract class MyAbstract
{
public abstract int get1();
public abstract int get2();
public abstract int get3();
}Interviewer was not convinced with following answers, he wanted to hear something else:
1. I have to extend MyAbstract and then I cannot have more extends, whereas in case of implementing MyInterface I am open to have inheritance.
2. I have to provide implementation of all three methods if used "implements MyInterface", whereas in case of "extends MyAbstract" I am open to carry forward abstractness.
3. Design perspective: All libraries work on interfaces not on abstract classes, it is good design practice to use interfaces so that at any time in future I can create any class (implements MyInterface) that can be used in some method of library. (basically same as point one)
What else there could be? I am not concerned with the variables in interface/abstract class etc. How to decide which one to use?
write an algorithm to change a infix sequence to postfix sequence
Find maximum number of distinct paths between two coordinates x1,y1 and x2,y2. where x2>=x1 and y2>=y1. and movement is allowed only in increasing direction, i.e. x1, y1 can move in (0, +1) means to the right and x1,y1 can move in (+1, 0) in the up direction.
A string contains only 0's and 1's, like 001010, swapping is permitted only with adjacent elements. Find an efficient way so that all the zero's are in the begining and the one's in the end. So the resultant string becomes 000011.
In this problem you have to write a program to check if two given binary trees are structurally equivalent.
Two trees are structurally equivalent if they are both null or if the left and right children of one are
structurally equivalent to the RESPECTIVE children of the other. In other words, when you draw the trees
on paper, they should LOOK alike (ignoring the values at the nodes).
The input to the program is a number N followed by N lines of input. Each line consists of a sequence of
positive numbers terminated by -1. There will be no duplicate numbers in any of the lines.
Construct a binary search tree with the input in the second line and use this as the basis-tree. For each of the
remaining N-1 lines, construct a binary search tree and compare against the basis tree for equivalence. If the
trees are equivalent, print YES else print NO. Also print the depth difference between the two trees (ie, depth
of the bigger tree minus the depth of the smaller tree). Both these for a given tree pair must be on one line
separated by a space. The answers for the different pairs must be on separate lines.
Sample Input/Output
Input
5
1 3 2 4 -1
4 1 2 3 -1
3 2 1 4 -1
4 3 2 1 -1
1 3 4 2 -1
Output
NO 1
NO 0
NO 1
YES 0
(Note that the depth difference will be zero if the trees are equivalent.)
Consider a service counter. People waiting for service form a queue. At the start, the queue is empty and
time is 0. The service time per person is 3 minutes.
The input to the program consists of an integer N followed by a sequence of integers indicating the arrival
time (in minutes) of the customers. These times are given as offset from the start of the simulation, so that an
input of 44 means 44 minutes from the start of simulation. The sequence of input numbers is terminated by
the number -1.
Your program must simulate the queue and print out the following:
1. The number of customers waiting in the queue at time = N minutes from the start of simulation.
2. The arrival times of the customers in the queue at that time, in increasing order.
Each integer must be separated by a space. Terminate your output with a newline character.
For doing the computation, you can assume that if the counter is expected to be vacant at time t, the first
person in the queue will be scheduled for service, before the counting is done for time t.
You must use the queue data structure to solve this problem.
Sample Input/Output
Input
9 0 2 5 6 6 8 10 -1
Output
2 6 8
Dr. Alberquert invented the following three devices to set up a simple communication network:
Synthesizer (S), which produces signals continuously and transmits (propagates / passes on) them to neighbouring cells but cannot receive signals.
Receiver (R), which can receive signals from neighbouring signal sources but cannot produce or propagate signal.
Transmitter (T), which is capable of both receiving signal from and transmitting signals to neighbouring cells. Transmitters also are NOT capable of producing signals.
These devices are laid in a matrix formation. Signals are propagated at the rate of one cell per time unit. The absorption rate of a receiver is unlimited and so also the transmission and absorption rate of a transmitter unlimited. For simplicity we shall ignore the exact nature of signals being produced and consider them uniform across sources. Devices on the extreme right side can also communicate with the extreme left hand side device present in the same row (see fig 2). Similarly a device on the extreme top can also communicate with a device at the extreme bottom if they are present in the same column.
Please Note:
Neighbourhood is a four cell neighbourhood, i.e, the neighbourhood of a cell is defined by cells to its NORTH, SOUTH, EAST and WEST (see fig 1).
All Synthesizers will start to produce signals as soon as the simulation begins.
There could be multiple Synthesizers in a matrix arrangement.
Your task is to write a program that would take a matrix containing devices and output the time at which each receiver/transmitter receives its first signal.
Input specification:
The first line has two integers M and N indicating the number of rows and columns of the matrix. 0 < M, N <= 20
M lines follow the first line. Each of these M lines contains N characters and a terminating new line. Each character is one of S, T or R.
Output specification:
The output should be a matrix of M rows with each row containing N integers separated by spaces indicating the minimum time required for the signal to reach the corresponding device. The output for cells containing Synthesizers is 0. For devices that never receive any signal, print -1.
Sample Input and Output:
Input:
3 4
SRTR
TTTT
TTTS
Output:
0 1 3 1
1 2 2 1
1 2 1 0
Input:
2 3
RTT
TTR
Output:
-1 -1 -1
-1 -1 -1
Given a matrix of order M x N containing 1.s and 0's, you have to find the number of maximal squares that can be formed. A square is formed by grouping adjacent cells containing 1. A maximal square is one that is not completely contained within another square. Maximal squares that overlap partially are to be counted separately. Unit squares (length of side = 1) should be also counted.
Note that squares are filled, i.e. they cannot contain 0.s.
Number of maximal square: 6
Input specification:
The first line consists of integers M and N, the number of rows and columns of the matrix.
0 < M and N <=40
Next M lines contain N characters from the set {0, 1}.
Output specification:
An integer representing the number of maximal squares that can be formed followed by a newline.
Sample Input and Output:
Input:
4 5
11001
11110
11011
11001
Output:
9
Input:
2 2
10
11
Output:
3
KingKong, the largest living ape, escaped from Xanadu lab into a forest. The forest is filled with dangerous animals, which will attack and kill human beings that venture too close to them. You are required to help the scientists find a way to get to KingKong safely. The table below gives the minimum distance one must keep from each species for safety.
Animal Name
Code
Safety distance (unit cell)
Lion L 1
Panther P 2
Both, the animals as well as the scientists can move only in horizontal or vertical directions. So, in the figure, the cells shaded gray are the cells into which the scientists must NOT venture, in order to be safe. The arrow shows that the panther is one vertical and one horizontal (a total of two) cell away from it.
A snapshot of the forest is obtained from a satellite picture in terms of an MxN matrix, which is the input to your program. This snapshot gives the location of various animals in the forest. Some cells might contain trees, which merely block the path of the scientists. The cells within the snapshot are marked by:
Animal code indicating the animal present in the cell
'T' in case of a tree present in the cell
'S', which indicates the start position of the scientists
'K', KingKong's location
'#', All other cells, which are empty
The output of your program should be the number of steps in the path that the scientists should take.
Notes:
There will be a unique path, if one exists.
The entire path including the starting position of the scientist as well as KingKong's location must be safe.
Input specification:
The first line contains two integers M and N the number of rows and columns. The next M lines contain N characters from the set {'L', 'P', 'T', 'S', 'K', '#'} as explained above
Output specification:
An integer specifying the length of the path, from the starting position of the scientist, to KingKong's position both inclusive. If KingKong is not reachable safely, then output the integer '-1'.
Sample Input and Output:
Input:
7 6
TLT#PP
LL####
LL#K##
TT##TT
TT#TTT
T###TT
TTTSTT
Output:
7
Input:
11 9
LL#######
L##TTTTT#
LKTTTTTT#
####P#TT#
###PP#TT#
####P#TT#
######TT#
L##T##T##
T##T####S
T####T###
TTTTTTLL#
Output:
-1
a tree is either:
- a branch with a list of child trees
- or a leaf with a value
@
/ | \
/ | \
@ D @
/ | \ |
| | | |
A B C E1) write a struct to represent it.
2) write a function f() to print out leaf values in in-order travesal
class InvalidTree {
};
template <class T>
struct tree {
vector<tree> child;
T* value;
// no empty tree is allowed
tree(vector<tree>& _tree, T* _t) {
if( !_t && _tree.empty() )
throw InvalidTree();
}
bool IsLeaf() const { return branch.empty(); }
T* GetValue() const { return value; }
const vector<tree>& GetChild() const { return child; }
};
template <class T>
void f(tree<T>* root) {
if(root->IsLeaf() ) {
cout << root->GetValue();
return;
}
vector<tree> childs = root->GetChild();
for(vector<tree>::const_iterator iter = childs.begin(); iter != childs.end(); ++iter) {
f(iter);
}
}You have been given three arrays A,B and C.
You have to find out all the elements in A and B such that the A[i]-B[j]=C[k]
How would you find out whether there is loop in a linked list or not ? Find out the point where the loop starts .
What will be the change in complexity if we will choose 2 and 3 pivots in the quicksort algorithm ?
The exact complexity and why ??
You are getting a stream of characters and at any time you can be asked to find out if the string received yet is palindrome or not.
There can be multiple queries.He insisted to do it in better than O(n) and No extra space.
we ahve an array of size 30 (say share price for 30 day of amazon in increasing order of day)
a[0] means first day price
a[1] means second day price like.
need to find the maximum loss in shares in these thirty day.
i gave algo of complexity of big o of n square (n=30 here).
we have one Array size of n.
suppose array name is a[],
it has property like
a[0] = 0
and a[n] = p (some value).
and in array every two consucative value will differ by most 1 only so the difference beetween any two consucutive value in array is either -1,0 or 1.
find the k in array such 0<k<p.
i give the algo having the complexity of o(n/k).
he want me to apply the binary search on this.
Provide an implementation of the stack functionality [i.e. LIFO] in a library. Since its going to be a library function, it can accept objects of any type.
- Write the APIs
- Discuss how you would structure the API's to handle objects of any type
- What data structure would you use
- Since its a library API that you are providing, keep in mind that you will be dealing with multiple stacks and that an object can be present in more than one stack
Question 1 / 1
There are K pegs. Each peg can hold discs in decreasing order of radius when looked from bottom to top of the peg. There are N discs which have radius 1 to N; Given the initial configuration of the pegs and the final configuration of the pegs, output the moves required to transform from the initial to final configuration. You are required to do the transformations in minimal number of moves.
A move consists of picking the topmost disc of any one of the pegs and placing it on top of anyother peg.
At anypoint of time, the decreasing radius property of all the pegs must be maintained.
Constraints:
1<= N<=8
3<= K<=5
Input Format:
N K
2nd line contains N integers.
Each integer in the second line is in the range 1 to K where the i-th integer denotes the peg to which disc of radius i is present in the initial configuration.
3rd line denotes the final configuration in a format similar to the initial configuration.
Output Format:
The first line contains M - The minimal number of moves required to complete the transformation.
The following M lines describe a move, by a peg number to pick from and a peg number to place on.
If there are more than one solutions, it's sufficient to output any one of them. You can assume, there is always a solution with less than 7 moves and the initial confirguration will not be same as the final one.
Sample Input #00:
2 3
1 1
2 2
Sample Output #00:
3
1 3
1 2
3 2
Sample Input #01:
6 4
4 2 4 3 1 1
1 1 1 1 1 1
Sample Output #01:
5
3 1
4 3
4 1
2 1
3 1
NOTE: You need to write the full code taking all inputs are from stdin and outputs to stdout
If you are using "Java", the classname is "Solution"
Hi all genius minds.
I have a small algorithm question. Any help will be appreciated.
Suppose there is a lake (some height lh) and then there are hills/mountains (with height from 0 to 9).
And finally there is Dam. All the hills and the lake and the dam are on a n*m matrix.
given the height of all points on matrix (lake and dam are also on one such point). find the minimum cost required to create a path from lake to dam so that dam can be filled with water.
Now height of each point can be increased or decreased except the lake.
water can flow only along the adjacent points not along the diagonals. Water can flow from point A to adjacent point B iff heightA >=heightB
-----------------------------------------------------------------------------------------
If we could only decrease the heights, this was a very easy question. but in current case heights can be decreased as well.
How do we solve this.?
Please revert for any clearifiactions
Two sorted array. Find kth smallest element
O(logK)
out of N 2D points, Find k nearest points to origin
I gave O(kLog(k)) solution
Given a matrix. Generate another matrix where each item M[i,j] is the sum of all elements in the matrix starting from origin and ending at i,j
Generate A to power B
I gave O(Log(B)) solution
You have an API to predict stock values of a particular share,
The API is
StockPrediction predict(int stockid);
where
class StockPrediction{
Date time:
float value;
}
using this API develop another API which will suggest the best selling time and buying time of a share (you have to call the predict API N number of times and from the StockPredictions provide the best buy time and sell time for the stock)
Your API can be BestTiming getBestTiming(int stockid);
where
class BestTiming{
StockPrediction bestselltime:
StockPrediction bestbuytime:
}
eg
values --> 10 12 7 8 24 35 1 9
time -----> 9am 9.30 9.45 10am 11am 12am 3am 4am
out put : buy the stock at 7 rs at 9.45 and sell it for 35 rupees at 12am
(hint: go for the best solution which uses only three variable to get this result)
Integer Array A of size N. Your job is to fill integer array B of size N where B[i] = products of all elements in A except the one at index i.
Simple solution prod = product of all elements in A
B[i] = prod/A[i]
Now to make it an interesting problem, can you solve it without using division operation?
Write a java program to do the breadth first search of a graph.
unsorted integer array with values 1 to N-1 has one duplicate element in it.
(N is the size of the array. max value is N-1 because of the duplicate element.)
Best way to find the duplicate element? If possible O(log n)
a cirle has points + and - and sigma of all ponits >0 we have to find the point where if we start journey always gives + tive partial sum at any point on the circle
Given two BST print the element in sorted form
complexity O(n) time maxm alloted space will be O(height of bigger tree)
eg ;
T1
3
1 5T2
4
2 6o/p 1 2 3 4 5 6
Design a File system for windows or linux machine. Use OO concepts.
Q1: Reverse a linked list without using recursion.
1->2->3->4->5->6
should become
6->5->4->3->2->1
Q2: Then reverse every K elements of a linked list.
1->2->3->4->5->6
should become
3->2->1->6->5->4
for k=3
Ans1: I used this method, but when i try and run this back home, I am not able to print the reverse of the linked list even though the function looks good.
It goes on to print the linked list in the same way as it did earlier. (Now Solved)
Can someone help me understand what is wrong here.
//Figured out the error, look at the correction in comments below//
Ans 2: Working on it (Not Solved)
//Reverse a linked list without recursion.
class link
{
int data;
public link nextlink;
link(int d1)
{
data = d1;
}
}
class List{
link head;
link revhead;
List(){
head = null;
}
boolean isEmpty(link head)
{
return head==null;
}
void insert(int d1)
{
link templink = new link(d1);
templink.nextlink = head;
head = templink;
}
void printlist(){
link head1 = head;
while(!isEmpty(head1))
{
System.out.print(head1.data + " ");
head1 = head1.nextlink;
}
System.out.println();
}
void reverse()
{
link previous=null,temp=null;
while(isEmpty(head))
{
temp = head.nextlink;
head.nextlink = previous;
previous = head;
head = temp;
}
}
}
public class LinkedList {
public static void main(String[] args) {
List list1 = new List();
list1.insert(10);
list1.insert(20);
list1.insert(30);
list1.insert(40);
list1.insert(50);
list1.printlist();
list1.reverse();
list1.printlist();
}
}2.) There is a paragraph of infinite length. WAP to find the length of words having maximum length of prefix.
Find out the complexity of the algorithm.
Amazon telliphonic 17 May, 2012
1.) There is a sequence where aphabets are written like this..
a,b,c,d,.......,x,y,z,aa,ab,ac........,az,ba,bb,bc,bd......bz,ca,cb.........cz........,aaa,aab,aac.....aaz,............zzz,aaaa...........zzzz..... and so on..
WAP to find out the string value at kth position.
like if k= 28 the string on 28 will be "ab".
What type of responsibilities are you seeking in a new role? What is your career objective? Why PayPal/Ebay ?
We have
char *p = "abc";
I know we cant do p[0] = 'a'. What is the reason behind it?
Given a set of numbers from 1 to n^2, generate subsets consisting of n numbers such that each subset has one and only one matching number from any other subset
The max number of sub-sets is n squared + n
An example is as follows:
n = 3
n squared set = 1, 2, 3, 4, 5, 6, 7, 8, 9
sub-set 1 = 1, 2, 3
sub-set 2 = 1, 4, 7
sub-set 3 = 1, 5, 9
sub-set 4 = 1, 6, 8
sub-set 5 = 2, 5, 8
sub-set 6 = 2, 4, 9
sub-set 7 = 2, 6, 7
sub-set 8 = 3, 6, 9
sub-set 9 = 3, 5, 7
sub-set 10 = 3. 4, 8
sub-set 11 = 4, 5, 6
sub-set 12 = 7, 8, 9
given 2 unsorted integer arrays a and b of equal size. Determine if b is a permutation of a. Can this be done in O(n) time and O(1) space ?
write a program to print the increasing order given the input :12/mar/2011..15/jan 1990,12/april/1985,23/dec/1960,11/sept/2004
the output will be
swap every two bits in an unsigned char .. eg swap bits at 0 and 1st position, swap 2nd and 3rd position, swap 4th and 5th position etc ..
Given two numbers "a" and "b" and an average formula (a+b)/2. Find one condition where it wont work. Also, give solution to it
You have an array containing n integers. Find a triplet a,b,c st a < b < c and a appears before b and b before c in the array. Suggest a solution with complexity less than O(n2)
How would you merge two binary search tree's ?
O(n) solution
Gave them a soln to do inorder traversal for both trees and merge the two sorted lists and create a tree out of the new list
How will you divide 100 such that you can make any number between 1 to 100 using them.
Ans 1,2,4,8,16,32,37 .How to prove this or get this GP any logic using proper mathematical proof...
We are given a binary search tree; we need to find out its border.
So, if the binary tree is
10
/ \
50 150
/ \ / \
25 75 200 20
/ \ / / \
15 35 120 155 250It should print out 50 25 15 35 120 155 250 20 150 10.
If the binary tree is
10
/ \
50 150
/ \ /
25 75 200
/ \ / \
15 35 65 30It should be like 50 25 15 35 65 30 200 150 10.
How can this be done? ?
given an array find the set of consecutive numbers which gives the maximum sum
I/P 1 3 -5 15 1 11 -15 18
o/p : 15+1+11 gives the maximum sum
the code should return 15,1,11
can u tell me the logic??
Thanks in advance
This was asked at Innovation labs (ILabs) Bangalore (24/7 Group Company.)
There is a river with N number of stones at different distance from the shore and you are on the shore. You need to cross the river by moving on each stone. Constraint here is, your next jump should be of {N, N-1, N+1 } any 1 from this 3. Sample input given is {1,2,3,5 ,8} These are the stone distances from the shore. So lets say if he jumps to 1, the next jump has to be, N+1=2, N-1=0 or N. Write a algorithm to find all the possible ways to cross the river and best among that.
I know that this needs to done with Dynamic programming using recursion. Can somebody write ?
You are given a function getInorderSuccessor which takes a BST (Binary Search Tree) as it's parameter. Every node has an extra pointer "next" , which is intialized to null, fill next with node pointers which represent Inorder Successor.
In a binary tree, inorder successor of a node is the next node in inorder traversal of the binary tree. Inorder successor is NULL for the last node in inorder traversal.
In BST, inorder successor of an input node can also be defined as the node with the smallest key greater than the key of input node. So, it is sometimes important to find next node in sorted order.
Sample Input :
Sample output.
The value of the node pointed by the next pointer is marked in { }
NOTE: The preorder of the tree you return would be printed to help you in debugging
You are given a function printKDistanceNodes which takes in a root node of a binary tree, a start node and an integer K. Complete the function to print the value of all the nodes (one-per-line) which are a K distance from the given start node in sorted order. Distance can be upwards or downwards.
Example:
Sample Input:
Root node: 5
Given start node: 8
Distance (K): 1
Sample Output:
5
6
9
In given array of elements like [a1,a2,a3,..an,b1,b2,b3,..bn,c1,c2,c3,...cn] Write a program to merge them like [a1,b1,c1,a2,b2,c2,...an,bn,cn].
PS: Do it without using extra memory
Sample Testcases:
Input #00:
{1,2,3,4,5,6,7,8,9,10,11,12}
Output #00:
{1,5,9,2,6,10,3,7,11,4,8,12}
Explanation:
Here as you can notice, the array is of the form
{a1,a2,a3,a4,b1,b2,b3,b4,c1,c2,c3,c4}
Given a sorted list but it is rotated. Find the start point in that list
Find the 3 letter substring in a string which also contains the reverse of that substring.
Ex: abcdefdcb This string contains bcd and its reverse dcb,
Print the sum of a binary tree
Reverse a String any lang you like
Given AAABBGFF should get an output 3{A} 2{B}1{G}2{F}
What is the next number in the series
2,4,8,16,24...
Q1.- Written exam (Amazon, Bangalore)
Given a singly link list and a number 'K', swap the Kth node from the start with the Kth node from the last. Check all the edge cases.
Sample Input: 1->2->3->4->5->6->7->8 and K = 3
Sample Output : 1->2->6->4->5->3->7->8
Sample Input: 1->2->3->4->5->6->7->8 and K = 10
Sample Output: print error "LIST IS OF LESSER SIZE".
Q2. F2F Round-1, Amazon(Bangalore)
Given an array of integers having the property that first that array is strictly increasing then it is strictly decreasing, You have to search for a given number.
Constraint: Minimize the complexity
Q1. F2F Round 1 Amazon(Bangalore)
Given a character array as input. Array contains only three types of characters 'R', 'G' and 'B'. Sort the array such that all 'R's comes before 'G's and all 'G's comes before 'B's.
Constraint :- No extra space allowed(except O(1) space like variables) and minimize the time complexity.
You can only traverse the array once.
Q4. Written Exam Amazon(Bangalore)
Given an array of integers A[1....n-1] where 'N' is the length of array A[ ]. Construct an array B such that B[i] = min(A[i], A[i+1], ......., A[i-K+1]), where K will be given.
Array B will have N-K+1 elements.
Constraint: Extra space allowed O(K) and time complexity allowed O(N.K) or lower.
Q3. Written Exam Amazon(Bangalore)
Given a singly linked list which may or may not contain loop and loop may or may not start from the head node. Count the number of elements in the linked list.
Q2. Written Exam Amazon(Bangalore)
Given a number in the form of string. Output the binary equivalent of that number.
Sample Input: "8.5"
Sample Output: 1000.1
Sample Input: "12.34.23"
Sample Output: "ERROR"
Q2. F2F Round-1, Amazon(Bangalore)
Given an array of integers having the property that first that array is strictly increasing then it is strictly decreasing, You have to search for a given number.
Constraint: Minimize the complexity
Q1. F2F Round 1 Amazon(Bangalore)
Given a character array as input. Array contains only three types of characters 'R', 'G' and 'B'. Sort the array such that all 'R's comes before 'G's and all 'G's comes before 'B's.
Constraint :- No extra space allowed(except O(1) space like variables) and minimize the time complexity.
You can only traverse the array once.
Q4. Written Exam Amazon(Bangalore)
Given an array of integers A[1....n-1] where 'N' is the length of array A[ ]. Construct an array B such that B[i] = min(A[i], A[i+1], ......., A[i-K+1]), where K will be given.
Array B will have N-K+1 elements.
Constraint: Extra space allowed O(K) and time complexity allowed O(N.K) or lower.
Q3. Written Exam Amazon(Bangalore)
Given a singly linked list which may or may not contain loop and loop may or may not start from the head node. Count the number of elements in the linked list.
Q2. Written Exam Amazon(Bangalore)
Given a number in the form of string. Output the binary equivalent of that number.
Sample Input: "8.5"
Sample Output: 1000.1
Sample Input: "12.34.23"
Sample Output: "ERROR"
Q1.- Written exam (Amazon, Bangalore)
Given a singly link list and a number 'K', swap the Kth node from the start with the Kth node from the last. Check all the edge cases.
Sample Input: 1->2->3->4->5->6->7->8 and K = 3
Sample Output : 1->2->6->4->5->3->7->8
Sample Input: 1->2->3->4->5->6->7->8 and K = 10
Sample Output: print error "LIST IS OF LESSER SIZE".
what is memory leak ?
which process / directory is responsible for the kernel is decompresed during boot up ?
given a pid, how will you distinguish if it is a process or a thread ?
Question DETERMINE THE OUTPUT R1,R2,R3 ARE THREE REGISTERS
START :POP R1
POP R2
COMPARE R2,0
JUMP_EQ DONE_Z
PUSH R2
PUSH R1
SUBTRATCT R2,1
PUSH R2
CALL START
POP R3
POP R1
POP R2
MULTIPLY R3,R2
JUMP DONE
DONE_Z:MOVE R3,1
DONE:PUSH R3
PUSH R1
RETURN
What value is returned by the following function? Express your answer as a
function of n. Give the worst-case running time using the Big Oh notation.
function mystery(n)
r := 0
for i := 1 to n − 1 do
for j := i + 1 to n do
for k := 1 to j do
r := r + 1
return(r)
how does Java do Garbage Collection?
implement shared_ptr in C++
template <class T>
class shared_ptr
{
private:
T* _t;
int *count;
public:
shared_ptr(T* t){
_t = t;
count = new int(1);
}
template <class D>
shared_ptr(shared_ptr<D>& d){
_t = d.Get();
count = d.GetCount();
*count = (*count)+1;
}
~shared_ptr() {
*count = (*count)-1;
if(*count == 0)
delete _t;
}
template <class D>
shared_ptr<T>& operator= (shared_ptr<D>& d) {
if( this->Get() != d.Get() )
{
*count = (*count)-1;
if( *count == 0)
delete _t;
_t = d.Get();
count = d.GetCount();
*count = *count + 1;
}
return *this;
}
T* Get() { return _t; }
int* GetCount() { return count; }
};There is an arithmetic expression with three operations: plus, minus, and multiplication, but an evil dwarf changed precedence of operators in a way that +/- had higher precedence than * when the expression was parsed. So as an input we get tree with wrong structure, and for example the expression:
a + b * c + d - eis represented as
*
/ \
+ +
/ \ / \
a b c -
/ \
e fConvert the tree to the right form taking into account that there can be parentheses but they group only expressions with + and -, i.e. the expression (a * b) + c is invalid input and should not be handled.
Explain the problem with following c code:
IN file1.c we define
int myarray[10];
IN file2.c we uses 'myarray' as,
extern int*myarray;
void foo()
{
myarray[0]=10;
}
Write a program to print all the permutations of the given input string.
In a multi-threaded process,If one thread is busy on I/O will the entire process be blocked?
Assuming there's no Array data structure in C, how would you implement it.
You have a stream of integers in ascending order and they keep coming – how would you find if a particular integer is in this array.
what are the different forms of IPC in UNIX?
what is better(why and how): multi processes OR single process with multiple threads?
what happens if the parent process ends before the child process?
how do applications communicate with kernel?
What is the contract between compareTo() and equals()
Find the minimum number of steps a knight should to kill the opponent in the game of chess (assuming the opponent does not move).
A huge file contains comma separated long values. File can not be accomodated in memory. WAP to find out the duplicate longs in the file.
Question: You have 25 bicyclists and 5 Bicycles. You have to find the best 3 Bicyclists in these 25. How many number races you will have to find the best 3.
These question are asked in Amazon written test for Testing Posts.
Question: You are using a phone which is having an problem that it gets switched off automatically within 2 minutes when talking in phone. Tell steps which you try to identify what the exact problem and if then tell the steps to resolve it.
Two words are friends if they have a Levenshtein distance of 1 (For details see http://en.wikipedia.org/wiki/Levenshtein_distance). That is, you can add, remove, or substitute exactly one letter in word X to create word Y. A word’s social network consists of all of its friends, plus all of their friends, and all of their friends’ friends, and so on. Write a program to tell us how big the social network for the word 'hello' is, using this word list https://raw.github.com/codeeval/Levenshtein-Distance-Challenge/master/input_levenshtein_distance.txt
Input
Your program should accept as its first argument a path to a filename.The input file contains the word list. This list is also available at https://raw.github.com/codeeval/Levenshtein-Distance-Challenge/master/input_levenshtein_distance.txt.
Output
Print out how big the social network for the word 'hello' is. e.g. The social network for the word 'abcde' is 4846.
given an array of positive integers A and the numbers N and S. Determine the number subsets of A of size S which sum up to N.
e.g. A[] = {1,2,5,3,6}
N = 9, S = 3
then we have 2 subsets of size 3: 1+3+5 and 1+2+6
Consider two singly linked list. Two linked list might or might not merge at a node. Find the merge node.
Implement the Indexof function to find a substring from a given string.
Consider a singly linked list of characters. Find if the linked list is palindrome or not. Without using another DS, in-place checking was preferred.
Consider a task which need to be scheduled. Need to maintain the detail of the task. Task can be executed by specifying some delay time. Design a task and function void Schedule(Task, delay). The task should have the capability to execute when CreationTime + delay is reached.
Given a BST. Replace the node value with the sum of all the node values that are greater than the current node value.
implement java code which takes aA1Bbc2@C3 as input and prints abcABC@6 as output
Given a graph based on a set of nodes and links, write a program that shows all the possible paths from 2 distinct nodes. It is up to you to decide what kind of structure you want to use to represent the nodes and links.
Example:
Let's say there are 4 nodes, named as 'a', 'b', 'c', 'd'.
And there are 4 links that connect 'a & b', 'b & d', 'a & c', and 'c & d', so that it will form a graph like the following:
---- b ----
a d
---- c ----
If the source is 'a', and the destination is 'd', your program should return:
a - b - d
a - c - d
You are given a function printKDistanceNodes which takes in a root node of a binary tree, a start node and an integer K. Complete the function to print the value of all the nodes (one-per-line) which are a K distance from the given start node in sorted order. Distance can be upwards or downwards.
x = x++ + ++y;
y = ++x + ++y;
what are the values of x,y after these are executed ?
reverse the words in a sentence: "hello world" -> "world hello"
given two integers and two bit positions. Set the first integer between the two bit positions to be that of the second integer.
implement sqrt(x)
Difference between constant char pointer and constant pointer to a char.
Code to find endianness of a machine.
* You are given 2 eggs.
* You have access to a 100-storey building.
* Eggs can be very hard or very fragile means it may break if dropped from the first floor or may not even break if dropped from 100 th floor.Both eggs are identical.
* You need to figure out the highest floor of a 100-storey building an egg can be dropped without breaking.
* Now the question is how many drops you need to make. You are allowed to break 2 eggs in the process.
Describe an algorithm to solve the following problem. Given an undirected graph G =
(V, E) and a vertex v, compute for each vertex w in the graph G the number of shortest
paths from v to w. Can we do it in O(|V| + |E|) ?
An cellphone company provides service on 7 different frequencies. They have fixed the locations of 100 towers for their new service. The company has to ensure that two towers broadcasting on the same frequency are at least 100 km apart, so that there is no interference of signals. Describe an algorithm which will answer “feasible” if it is feasible, otherwise output the minimum
number of frequencies needed to utilise all 100 towers.
Given an undirected graph. Each vertex has degree at most 5. Give an algorithm to find the largest clique in G. What will be the complexity ?
Only designing idea will be sufficient.
Consider a plate stacked with several disks, each of a different diameter. We want to sort these disks in decreasing order according to their diameter so that the widest disk is at bottom of the pile. The only operation available for manipulating the disks is to pick up a stack of them from the top of the pile and invert that stack.
Give an algorithm for sorting the disks using this operation.
Write an algorithm to preprocess a list in O(n) time such we can find sum(i,j), i,j E A[ ] & i<j in O(1) time
There are 1000 balls in a bag, of which 900 are black and 100 are white. I randomly draw 100 balls from the bag. What is the probability that the 101st ball will be black?
a)9/10 b)More than 9/10 but less than 1 c)Less than 9/10but more than 0 d)0 e)1
Amar and Akbar both tell the truth with probability 3/4 and lie with probability 1/4. Amar watches a test match and talks to Akbar about the outcome. Akbar, in turn, tells Anthony, "Amar told me that India won". What probability should Anthony assign to India's win?
a)9/16 b)6/16 c)7/16 d)10/16 e)None of the above
Implement a LRU Cache. 1st tell pseudo code then write clean code.
Implement JAVA code which takes 2 dimensional integer array as input and prints out heaviest island.
Write a code that will check whether the memory allotted to the program at the initial and the memory returned to the system is same or not.
write a function
int dominator(const vector<int> &A);
that, given a zero-indexed array A consisting of N integers, returns index of any element of array A in which the dominator of A occurs. The function should return -1 if array A does not have a dominator.
Assume that:
N is an integer within the range [0..1,000,000];
each element of array A is an integer within the range [-2,147,483,648..2,147,483,647].
For example, given array A such that
A[0] = 3 A[1] = 4 A[2] = 3 A[3] = 2 A[4] = 3 A[5] = -1 A[6] = 3 A[7] = 3
the function may return 0, 2, 4, 6 or 7, as explained above.
Complexity:
expected worst-case time complexity is O(N);
expected worst-case space complexity is O(1), beyond input storage (not counting the storage required for input arguments).
time consuming of removing space from a string.
remove spaces when they occur more than one time consecutively in string.
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define SPACE ' '
main()
{
char string[100], *blank, *start;
int length, c = 0, d = 0;
printf("Enter a string\n");
gets(string);
length = strlen(string);
blank = string;
start = (char*)malloc(length+1);
if ( start == NULL )
exit(EXIT_FAILURE);
while(*(blank+c))
{
if ( *(blank+c) == SPACE && *(blank+c+1) == SPACE )
{}
else
{
*(start+d) = *(blank+c);
d++;
}
c++;
}
*(start+d)='\0';
printf("%s\n", start);
free(start);
return 0;Implement a bi-directional map in Java. Given a key, map should return corresponding value and given a value, it should return the key.
Given a BST, convert it so that each node has value equal to sum of all the nodes (including itself) which are greater than that node in the whole tree.
You are given a string of ‘n’ characters where n is even. The string only consist of 6 type of characters: (){}[]. The task is to form a well formed expression. A well formed expression consist of proper nesting of braces and their is no priority between the braces like [ > } > ). You can edit any bracket and change it to remaining types for accomplishing the task.
Example
A. "(){}" is valid
B. "({[]})” is valid
C. “((})” is invalid
Given an array having positive integers, find a continous subarray which adds to a given number.
A log of wood has n marks on it. Cost of cutting wood at a particular mark is proportional to the length of the log. The log of wood can be cut at all the marks. Find the optimal order of the marks where the log should be cut in order to minimize the total cost of cutting.
What is the output of:
main ()
{
printf("%x", -1<<4);
}What does the following program do ?
main ()
{
unsigned int num ;
int i ;
scanf("%u ", &num);
for(i=0;i<16;1++)
printf("%d",(num<<i & 1<<15) ? 1:0);
}
A. print all even bits from num
B. print all odd bits from num
C. prints binary equivalent of num
Are all the system calls interfaced in glibc ?
What are the steps in a core generation after a panic is hit ? What all does a core contain, basically what all data, segments you can access.
You are given a positive integer A. The goal is to construct the shortest possible sequence of integers ending with A, using the following rules:
the first element of the sequence is 1,
each of the successive elements is the sum of any two preceding elements (adding a single element to itself is also permissible),
each element is larger than all the preceding elements; that is, the sequence is increasing.
For example, for A = 42, a possible solutions is [1, 2, 3, 6, 12, 24, 30, 42]. Another possible solution is [1, 2, 4, 5, 8, 16, 21, 42].
You are given a positive integer A. The goal is to construct the shortest possible sequence of integers ending with A, using the following rules:
the first element of the sequence is 1,
each of the successive elements is the sum of any two preceding elements (adding a single element to itself is also permissible),
each element is larger than all the preceding elements; that is, the sequence is increasing.
For example, for A = 42, a possible solutions is [1, 2, 3, 6, 12, 24, 30, 42]. Another possible solution is [1, 2, 4, 5, 8, 16, 21, 42].
Write code to remove a node from a linked list. Choose the node which would be most efficient to remove.
Hint: Head node.
Reverse an array without using iteration.
Hint: Recursion.
Write functions for insertion and deletion in a circular queue implemented using an array in C.
Hint: Remove the node from the end.
Add a node in the front. Move the pointer for removal and insertion. Pointer is just a counter for the index. Modulus it by size of array so that it circles from 0-n.
When pointers match , array is full.
Given an array of integers, return the first integer which occurs only once in O(n).
Is singleton a class level OR JVM level implementation?
Is singleton a class level OR JVM level implementation?
If my hashcode() method returns zero will it compile, run or throw error?
Is it good practice for hashcode() method returns zero?
support we have an input file while contains integers in the following format
3
8 5
2 3 1
0 7 4 2
basically line N has N integers. starting from line 1, find the adjacent numbers in the following line and get the max total from top to bottom. in the above case, the sum is 3+8+2+7=20
Print All common ancestor of Given Binary tree in O(n)
without using Extra space.
What happens if you make a field both final and volatile?
find the length of string without using inbuilt methods in java
Find the kth smallest element in a sorted array
Find the kth smallest element in a (MxN) matrix.
find the number of integral solution of
1/x+1/y=1/n!
What is virtual function?
Why we need pure virtual function?
Give real time example of, dynamic link library. How your program links dynamically?
1.
x = 5; y = 6;
x = y++ + x++;
y = ++y + ++x;
printf("%d.....%d", x, y);2. How function pointer works?
3. **p vs &(*p)
4. int a[10]; how you allocate memory for the same; should be compiler independent.
Write a program to:- Finding the “Nth node from the end” of a linked list
given a NxM matrix , where each array entry is a character, we need to find all the valid words that can be formed using elements in a row, column and diagonal. like crosswords puzzle.
We are given a dictionary and a function
boolean isValid(String word)
which returns whether the word passes to this function is valid dictionary word or not.
Given a date as 2001/10/02 it is a palendrom , find the palendrom date that will occur just after this.
Please give just approach.
If there are 1 million files in Amazon database, there is a wrong area code of customer phone number. How would you debug?
Write code to check the string is palindrome
Design a multiple elevators system of skyscraper. Design an algorithm to let person find available elevator soon. How to improve your algorithm?
#include <cstdlib>
#include <iostream>
using namespace std;
class Empty
{};
class Derived1 : public Empty
{};
class Derived2 : virtual public Empty
{};
class Derived3 : public Empty
{
char c;
};
class Derived4 : virtual public Empty
{
char c;
};
class Dummy
{
char c;
};
int main(int argc, char *argv[])
{
cout << "sizeof(Empty) " << sizeof(Empty) << endl;
cout << "sizeof(Derived1) " << sizeof(Derived1) << endl;
cout << "sizeof(Derived2) " << sizeof(Derived2) << endl;
cout << "sizeof(Derived3) " << sizeof(Derived3) << endl;
cout << "sizeof(Derived4) " << sizeof(Derived4) << endl;
cout << "sizeof(Dummy) " << sizeof(Dummy) << endl;
system("PAUSE");
return EXIT_SUCCESS;
}and the out put is (In Dev c++)
sizeof(Empty) 1
sizeof(Derived1) 1
sizeof(Derived2) 4
sizeof(Derived3) 1
sizeof(Derived4) 8
sizeof(Dummy) 1
why the size of derived2 is 4 and the size of derived 4 is 8.
Write a program to check if a binary tree is a binary search tree
Write an algorithm to split a circular linked list two linked list with equal no of nodes
in an array n/2 elements are repeated. las vegas algo to find the element. runtime is o(log(n)). follow up question:- minimum number of elements to be repeated to keep the runtime o(log(n)). next :- what is the runtime if repeated elements is root(n).
Can someone Please help.
You need to write a code to Reverse a n-ary tree a return the leaf nodes. The given Input is the root node only. Code in Java using List.
Given a 2D array of 1's and 0's, find the size of the largest block of 0's. For example the following 2D array:
int[][] array = {
{1, 0, 1, 0, 0, 0, 1, 0 }
{1, 0, 0, 0, 0, 0, 1, 1 }
{1, 1, 1, 0, 0, 0, 1, 1 }
}Would return "9", because there is a 3x3 square of 0's, and that is the biggest block of 0's in the 2D space.
You play a dice rolling game, you have two choices:
1. Roll the dice once and get rewarded the amount of $ equal to the outcome number (e.g, $3 for number "3") and stop the game;
2. You can reject the first reward according to its outcome and roll the dice the second time and get rewarded in the same way and stop the game.
Which strategy should you choose to maximize your reward? (that is what outcomes of the first roll should make you play the second game?)
What is the statistical expectation of reward if you choose that strategy?
Given N points(in 2D) with x and y coordinates. You have to find a point P (in N given points) such that the sum of distances from other(N-1) points to P is minimum.
Given an n-ary tree, find the closest common ancestor ? Discuss the time complexity and write testcases.
given an unsorted array of integers. given d. U need to find all the pairs having difference d.
I solved in nlogn. any better algo.
write a method to solve a maze. there should be 3 inputs for the method, start point, end point and maze itself. how to represent the maze itself?
X is the start point, Y is the end point, and find the path in the maze
X
| |
| |________
|__________Y
Given the following structure in memory
Name State City Street
David CT Stamford main st
Cindy MA Boston huntington ave
Grace NY New York kissena blvd
Ted FL Miami lexington ave
give an data structure and algorithm for providing queries:
given any "State" or "State + City" or "State + City + Street" and return all names
give any "Name" and return all "State + City + Street"
make sure the algorithm is efficient for millions of such records
Find the all the sequence from Unsorted array.
Example : {2,4,6,8,10,14,11,12,15,7} is the unsorted array. We have to find out possible sequences.
Output would be :
Seq 1 : {2,4,6,8,10,11,12,15}
Seq 2 : {2,4,6,8,10,14,15}
Note : if I pick any element in array than next element would be grater than the previous element.
there are two processes p1 & p2
P1 : read the file
P2 : modify the file
how will u synchronize the process so that modify can happen only when no one is reading the file. Using constructs
Enter Critical Section :
Exit Critical Section :
Wait Event :
Signal Event
you are given pair of no's wap which will merg the overlaping pair's and print out the final result
for eg. given pair's (1,3), (2,4),(5,6)......
2 comes between 1&3 so first 2 pairs shud be merged
n out put will be (1,4),(5,6)......
i took 30 min approx to solve it and finally came up with a O(n^2) solution
any one have a solution whose complexity is be better than this????
Given a dictionary of strings [ strings are in sorted order] you have to find the precedence of characters according to the dictionary..
eat
bxy
e is ranked above b according to the dictionary.
N players played in a tournament and the results are out. Each player has played all other players. To print out a combination 1,2,3, .. , i-1, i, i+1,....n such that i-1 has lost to player i and player i has lost to i+1.
What would be the complexity for the same?
Given a BST and a integer k. Wap to print all pairs of two numbers with sum k.
pairs should be different.
ex. {2,4} and {4,2} are same so only one gets printed
Assume all the numbers in BST are different.
Determine if the given string is of form pZq.
q consist the reverse of p.
and p and q will consist only X and Y.
for ex. p=XYXX and q=XXYX(reverse of p). then
string XYXXABXXYX is a valid string.
The constraint is : you can access only next character at each point.
What is a process.
What is a stack.
How many stacks can a process have.
What is a thread.
How many threads can a process have.
Do the threads have their own stacks, or share the process stack(s), or both?
write a program to implement doubly linked list as a circular linked list
write a program to implement stack as a circular linked list
print 2n+1 prime numbers if any one of them not prime then print factors for that number
write a program to print the given string as alphabets in order next integres fallowed by sum
example: CAE2W3A is input and output should be
ACDEW5
what is the output
main()
{
char x=-1>>2;
printf("%d",x);
}
Implement a stack with 3 operations: push, pop and findmiddle(). At any point in time, findmiddle() should return the middle element of the stack (n/2+1) without popping out the elements. ie. in O(1) time
Give you an array of String,
return number of distinct strings in that array.
Randomly return a node in a binary tree, program in C/C++, and define the class or struct of the binary tree by yourself.
Interest problems:
when you deposit a mount of money x1 in a one year , then you get amount of money x2 in n years later. the interest rate R, x1 and x2 is known, calculate n. Write a C/C++ API, return the year. The rate is compound interest rate.
Identify whether an math expression is legal.
for example: {[3*(3+2)]+1}*5 is legal
{(]3++}+4 is illegal
How to test a whiteboard?
Reverse the word in a string.
for example:
"hello world" after is
"olleh dlrow"
desgin test cases
print out the start and end index of the subarray that has the largest sum in an integer array.
Design test case
return the 2nd largest number in an integer array, then design test cases:
Suppose you have a graph G(V,E).
You are supposed to find the shortest path from a vertex 's' to vertex 'e' for 'n' different cases.
In each case one of the edges 'Ei' (any one edge) of the graph will be blocked/deleted only for that case and we have to find the shortest path in the graph with that edge removed.
Guys finding the shortest path is easy. But how can I make the algo so fast that even if I remove one of the edges my algo should still be very fast. O(n log n) or faster.
Remember we are not deleting the edges permanently. We are just temporary removing one edge per case.
In each case only one edge is removed.
Suppose we blocked one edge E in one case. We have to find the shortest path for the graph.
In next case, we will reconnect the last edge and we will block/remove a new edge. And again for this new case we have to find the shortest path.
Another way of understanding the problem is suppose there are cities connected to each other.
And every day one of the roads gets blocked because of heavy rain. what is the shortest path every day from city s to e.
Also one more important thing to note that each road can be used only once.
But there could be more than 1 direct road from city a to city b.
FInd the shortest path distance from city s to e on a day when all direct roads from city f to city h are blocked. If there is no connecting path return -1
what is complexity of the code
for(int k=1;k<n;k++)
{
j=k;
while(j>0)
{
j=j/2;
}
}
given three strings X, Y and Z. Find all solutions to a numeric puzzle: X + Y = Z where each character in a string corresponds to some digit.
For simplicity, you may assume that strings are of the same length.
e.g.: X = "abcd", Y = "dbcc", Z = "cdda"
hence we get: 2275 + 5277 = 7552
Implement the stack using single Queue
How do we decide which column we should partition on and which column to index on
Table TEAM( TEAM_ID, TEAM_NAME).
This table has all the football team names.
Say entries are
1 France
2 Germany
3 Spain
Write a SQL to generate match Fixtures between the teams. No hard coding. No repeation.
Sample out put will be
C1 C2
France Germany
France Spain
Spain Germany
Given X different vectors. Find the combined median in an efficient way
Discuss both when they are sorted and not sorted
Given a number. And one permutation of that number. Find out in how many steps can you get back to the original number from the permutation if you use the same mapping again and again. If its not possible, then state so.
Example: 2315 -> 5213
So in this example Mapping is number at 1st index -> 2nd index
2nd index -> 4th index
3rd index -> 3rd index
4th index -> 1st index
So using same mapping can we come back to 2315. If yes then in how many steps?
consider binary representation of all numbers
1 : 1
2 : 10
3 : 11
.
.
.
7 : 1 1 1
...
how many ones are requred to write numbers from 1 to n.
eg how many 1's are needed to write numbers from 1 to 7 : 12
expected complexity : logn
Given a string. Tell its rank among all its permutations sorted lexicographically
consider any string of characters
aabbbccdeef
break it into partitions such that each partition is a palindrome
aa|bbb|cc|d|ee|f so 6 partitions
pow(a,b) = a*a*a ...*a (b times)
consider pow(2,i)*pow(3,j) * pow(5,k)
where i,j,k are whole numbers.
so the possible numbers that can be written in this format are
1,2,3,4,5,6,8,9,10 ....
quesiton was to print nth number in this series (say 100th)
expected complexity : O(n).
print all palindromes of size k possible from given alphabet set.
eg alphabet set : {a,e,i,o,u}
print all palindromes of size say 10.
find the bug in the given source code
main()
{
char x=300,y;
y=300*300/x;
printf("%d",y);
}
If given a variable that is changing after every 1 second...
Design a clock using that avriable..
I am not sure if this question was more related to OS or not...
There is a tree with additional field in each node, named "next". We have to put the inorder successor in this pointer.
How to find if a number is a power of 2?
How to find if a point lay inside a triangle?
print all compositions of a number in odd parts, i.e. for n = 8:
7 + 1
5 + 3
5 + 1 + 1 + 1
3 + 3 + 1 + 1
3 + 1 + 1 + 1 + 1 + 1
1 + 1 + 1 + 1 + 1 + 1 + 1 + 1
what is difference between " return " and " exit ".
wap to input any number and double it without using any operator
Given two strings, find that the if the letters in both the strings are same? i.e. can we be able to make string2 out of string1 by shuffling the words and vice versa.
Given two classes like animal and dog class where dog class inherit the animal class. Write a function which will return deep clone instance
Write a code to find out whether the given sum exists over any path in binary tree. Should return true or false.
Write a thread-safe array-based queue implementation in java. If one thread reaches to limit, should wait for dequeue thread to create a space and vice-versa.
Given two classes like animal and dog class where dog class inherit the animal class. Write a function which will return deep clone instance
To find a maximum profit index from a give array with O(n) complexity.
given a file with x,y,z coordinate which refer to the coordinates of stars relative to earth, how would you find the first 100 stars nearest to earth? the coordinates are unsorted in the file.
given an unsorted array how will you find the duplicate entries in that array?
interviewer, do you know what is an expression tree?.I said No.Than he explained.
He asked me to computer the value of the expression tree.
%
1 +
5 8
How to solve this. It took me 30 minutes to get the answer?.
Write a program for binary tree (not BST) where left is connected to right and the whole structure is connected.
Design File System. Interviewer said just code and no OOP
WAP to find the word "amazon" in a given m*n matrix.
The characters need not be allocated in a line eg:
lets consider a 3*3 matrix
h j z
e a o
a m n
this is a valid case as the string is in contiguous form in the lower half of the matrix, while
a j z
e a o
h m n
is invalid.
Function should return true or false.
have 1 million product id, get the top 10 in the past 1 hour
large file(can't fit into memory) with multiple lines, how to get any line in equal probability
design a library for borrowing books and renewing
design a zoo with different types of animals and cages(type, size), some of them cannot be in same cage.
how to represent relationship? what if lion eat 1 million different animals?
customers want to buy some products but products are out of stock, design a system to notify them when those products are again available?
Design DVD renting system, database table, class and interface
next permutation of a given number
power set of a set
rebuild binary tree with pre-order and in-order sequence
Serialization & Deserialization of Binary Tree
What is the size of char,long and short in 32 bit architecture and 64 bit architecture?
We have n punching bags in a row. Mr Lee is going to practice with them for the upcoming Boxing tournament.
Each bag has a resistance level. Mr Lee can punch a bag if its resistance is greater than 0. He is an extremely hard puncher: when Mr Lee punches a bag, not only is its resistance set to 0 (ie: the bag is destroyed), but also the resistances of its immediately adjacent neighbors( one on left and other on right ) are decreased by one. If at any point of time the resistance of a bag drops to zero or less it is considered as destroyed. A punch on a bag with resistance greater than 0 has no impact on an immediate neighbour which is already destroyed.
Mr Lee wants to maximize his (very expensive) workout sessions, and would like to punch on these bags as much as possible. For any set of punching bags, what is the maximum number of punches that he can perform?
Input Format
On the only line of input there are n characters describing the resistances of the bags from 1 to n.
Ouput Format
On the only line of the output print an integer describing the maximum number of punches Mr Lee can punch for that set of bags.
Sample Input
11
Sample Ouput
1
Sample Input
021
Sample Output
2
Explanation
In the first example there are two bags, and we can punch only one of them before destroying both. In the second example we can punch on the third bag and then on the second bag to obtain two punches.
Constraints
Each bag has a resistance level between 0 and 3 ( inclusive ) and the number of bags is not more than 100.
Given a sequence of integers a[1],a[2],...,a[n], we call a sequence b[1], ..., b[m] an alternating sequence if:
for every odd 1 < i <= m, we have b[i] < b[i-1],
for every even 1 < i <= m, we have b[i] > b[i-1].
Given a sequence of integers a[1], ..., a[n], your program must find the length of the longest alternating subsequence. (we define a[i1], ..., a[im] to be a subsequence if 1<=i1< i2<...<im<=n.)
Input
First line of input contains the length of sequence n (1<=n<=200,000). The second line contains n space seperated integers a[1], ..., a[n] (1 <= a[i] <= 10^9).
Output
Output is just a single integer number which denotes the length of longest alternating subsequence.
Sample Input
10
1 2 3 4 5 6 5 4 3 2
Sample Output
3
Explanation: On many alternating subsequences of length three, some are 1 6 2, 3 5 3, 4 6 2 etc. There is no alternating subsequence of length greater than three.
Note : A sequence with just two elements, such that the second element is greater than first is a valid alternating sequence. Moreover a sequence with only one element is also considered an alternating sequence.
Design a structure for a student record which has following 3 fields-
ID - integer value
Name - String
either a grade - which is float value OR rank - which is integer value.
Also write a function to print the details of a student record such that if the student is given grade it must be printed as float value but if he is given rank then it must be printed as integer value.
Write a function in C to efficiently copy 1 file to another.
A node of a binary tree has two pointers left and right and two data fields- left count and right count. left count specifies the number of nodes in left of the node and right specifies the number of nodes in right of the node. Write an algorithm to populate the data fields of all the nodes of the tree.
Write a function for reversing a doubly linked list.
Given a binary number in string form, write a function to return its two's complement in string form.
Print all the increasing subsequence from the given range 54782369862345 .. ex: 5,7,8,9; 4,7,8,9; 2,3,6,9 ..
using Recursion
Hi.. i had an inperson interview in a small startup company and i was asked to code.. the ques is as follow. I need to asume about the microprocessor and detectors in the US roads which detects the cars passing o the road. so i need to count 1 for every sec and prnt total no of sec, if the detecter detects a car passing by i need to say 2 and print the number of cars passed and also i need to calc the maximum time difference betwesn the two cars which passed.. if anyone knows the soln please post it. and he gave me a methos int getevent() and i was asked to write all these withing this method and all shuld be whithin just one loop.
You are a hacker and you a length of password...the password is perfectly ordered...like 123 is valid but 132 is not valid cos 1<3 but 3>2...so print all the ordered passwords.
You are a hacker and you a length of password...the password is perfectly ordered...like 123 is valid but 132 is not valid cos 1<3 but 3>2...so print all the ordered passwords.
You have to take a string or a line as an input from the user and apply two rules to it:
1. if the letter is a vowel like 'e'...convert it to 'E' and if its a "E"..convert it to 'e'...same for all the vowels. However the first letter has to be Capital.
2. if its a consonant, let it be as it is but if the consonant is the first letter of the sentence make it capital
For eg: bEes ARe Busy...will become
BeEs arE bUsy
If you guys have played othello or reversi, this is the game that they asked, but all the moves for red and black were passed in a boolean array to us. We just have to find who is the winner of the game, if for a sequence of 3 u get 1 point, for a sequence of 4 u get 2 points, for sequence of 5 u get 3 and so on.. Sequences can be horizontal,vertical or diagonal...the output of the program should be who won the game...red or black.
The same Glitch Robot question whihc is posted on the nexxt page with the only variation that the robot makes a turn every 100 steps...I found this question tuff and it consumed a lot of time.
Write a program to find all occurance of a given substring a given string.
Without using /,% ,+and * operators. write a function to check whether a number is divisible by 3 or nor??
print a tree with label wise in given that scenario
15
12 23
9 16 17 35
Given a set of numbers from 1 to n squared, generate unique sub-sets consisting of n numbers such that each subset has one and only one matching number from any other sub-set
The max number of sub-sets is n squared + n
An example is as follows:
n = 3
n squared set = 1, 2, 3, 4, 5, 6, 7, 8, 9
sub-set 1 = 1, 2, 3
sub-set 2 = 1, 4, 7
sub-set 3 = 1, 5, 9
sub-set 4 = 1, 6, 8
sub-set 5 = 2, 5, 8
sub-set 6 = 2, 4, 9
sub-set 7 = 2, 6, 7
sub-set 8 = 3, 6, 9
sub-set 9 = 3, 5, 7
sub-set 10 = 3. 4, 8
sub-set 11 = 4, 5, 6
sub-set 12 = 7, 8, 9
Write the C++ algorithm that will work for any arbitrary integer value n. The n-squared set can be placed into any built in C++ data structure eg 2d array.
Given a character array. Find if there exists a path from O to X. Here is an example
. . . . . . .
. . . . . . .
w . . . . . .
w .w.w..
. . . . O . .
. . w. . . .
. . . X . . .
You have to just keep in mind that you cannot go through 'W'.
Write a program for Palindrome
how do you count set bits in a Float number?
you have only two functions
1.Loop(count) : Loops for count times
2.Increment(Count): increases a number count times
How would you achieve A-B using only these two operations?
Remember you have no operation like comparison,bit-wise operations or anything, just these two you have......
there two article:A ,B,which is very large. get three or more successive words in A,to find if it appears in B ,and count the times. For example , 'book' 'his' 'her' appear in A ,how many times it appears in B?
there two article:A ,B,which is very large. get three or more successive words in A,to find if it appears in B ,and count the times.
For example , 'book' 'his' 'her' appear in A ,how many times it appears in B?
I give a solution which time complexity is not good,who can give a better solution ?
Insert an element in a ordered (ascending) circular linked list. After inserting return the node with the smallest element.
Given the coordinates of N points in a plane. Assume the standard 2D quadrant system for representation of points.
Problem is - Find the centre and radius of a circle which passes through the maximum number of points. The centre must be one out of the given N points.
Given the coordinates of N points in a plane. Assume the standard 2D quadrant system for representation of points.
Problem is - Find the centre and radius of a circle which passes through the maximum number of points. The centre must be one out of the given N points.
Return true if two trees are same
An array has duplicate elements each elements occurs even number of time except one occurs odd number of times. Print that number. Provide the complexites of the solution
Difference between LinkedList and arraylist as to what are the advantages of LinkedList
input linked list is : 1->9->3->8->5->7->7
do you see any pattern in this input ?
odd placed nodes are in increasing order and even placed nodes are in decreasing order.
write a code that gives the the following linkedlist:
output linked list should be 1->3->5->7->7->8->9
?? can it be done inplace ?
Is there a restriction on the types of objects that can be stored in an NSDictionary?
Is there a restriction on the types of objects that can be serialized?
What is an NSDictionary and how would you implement it?
What is a protocol?
Are you familiar with the object send method?
Where in the Model-View-Controller would you find the NSCoder protocol being used?
What is the big-O algorithmic complexity of insertions, deletions, and find operations in a binary tree?
What is the big-O algorithmic complexity of insertions, deletions, and find operations in a hash table?
What are the ways to extend classes in Objective-C?
What is the NS Coding Protocol?
What are the five most commonly used Objective-C objects?
Explain dynamic binding?
When a child is forked then it inherits parent's file descriptors, if child closes the file descriptor what will happen ? If child starts writing what shall happen to the file at the parent's end ? Who manages these inconsistencies , kernel or user ?
Design a Vending machine. Give the classes and the test cases.
Write a Program
You will create an employee class with the following properties:ID (int), FName(string), LName(string).
(Functionality) to track an employee's manager and subordinates.
Add a method that displays the names of all subordinates for a given employee.
Calculate the complexity. Do not use multiple classes.
regular expression matching: given a regular expression just composed with letters and *, whether a string str can be generated by the regular expression? for example, regular expression a*b*c , the string aabaabc cann't be generated by the regular expression.
Which is better to use - binary semaphore or mutex
What is the difference between kill-6 and kill -9
Consider this string representation for binary trees. Each node is of the form (lr), where l represents the left child and r represents the right child. If l is the character 0, then there is no left child. Similarly, if r is the character 0, then there is no right child. Otherwise, the child can be a node of the form (lr), and the representation continues recursively.
For example: (00) is a tree that consists of one node. ((00)0) is a two-node tree in which the root has a left child, and the left child is a leaf. And ((00)(00)) is a three-node tree, with a root, a left and a right child.
Write a function that takes as input such a string, and returns -1 if the string is malformed, and the depth of the tree if the string is well-formed.
For instance:
find_depth('(00)') -> 0
find_depth('((00)0)') -> 1
find_depth('((00)(00))') -> 1
find_depth('((00)(0(00)))') -> 2
find_depth('((00)(0(0(00))))') -> 3
find_depth('x') -> -1
find_depth('0') -> -1
find_depth('()') -> -1
find_depth('(0)') -> -1
find_depth('(00)x') -> -1
find_depth('(0p)') -> -1
How do you not know this?
(After a missed technical question.)
(Backstory: This interview is for the fifth job I've interviewed for at Apple this semester. This question arose in a phone conversation with HR.)
HR: (Snarky Tone) So what did you learn from your past three interview experiences with Apple?
Me: I learned that at Apple, whatever subspecialty for whatever job your applying for, you have to be the best in the world. If you have equivalent skill, but someone has more work experience than you, there always going to pick the person with more work experience, and coming right out of college, that means you don't get the job. I had asked my interviewer during one of my interviews, "Do people move around at Apple?" and she said "No, most people don't move around at Apple, they usually leave Apple. You're not going to learn how to do someone else's job at this job."
HR: Awkward silence...
How do I answer this question more professionally and succinctly? Why was the conversation awkward after I had made my remark?
What are you looking for?
Me: " I'm looking to work in a software engineering position at Apple because I really enjoy building projects with iOS."
Interviewer: "Is that all you've got? haha."
Question: How do I respond to this?
How does memory management work in Objective-C?
(Me: I've had this question five times already.)
Well then, explain to me how Automatic Reference Counting works?
- (void)setFinishedSelectedImage:(UIImage *)selectedImage withFinishedUnselectedImage:(UIImage *)unselectedImageHow would you automate testing for this method?
Given a two lists, list A with size N, and list B with size M, write an algorithm to find all of the items that are in both list A and list B.
N is large ~ at least 20,000
M <<< is single digit length
Cases:
(i) M <<< N
(ii) M < N
(iii) M = N
Implement the find substring method in c++ which takes two input, the string, and the substring to look for, and returns the start index of the first occurrence of the string.
Implement a stack-based linked lists for generic objects in c++?
How do you allocate a singleton in Objective-C?
//
// UIAccelerometer.h
// UIKit
//
// Copyright (c) 2007-2011, Apple Inc. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <UIKit/UIKitDefines.h>
/* UIAcceleration and UIAccelerometer are deprecated as of iOS 5.0. These classes have been replaced by the Core Motion framework. These classes will be marked with formal deprecation attributes in a future release of iOS.
*/
typedef double UIAccelerationValue;
@protocol UIAccelerometerDelegate;
UIKIT_CLASS_AVAILABLE(2_0)
@interface UIAcceleration : NSObject {
@private
NSTimeInterval timestamp;
UIAccelerationValue x, y, z;
}
@property(nonatomic,readonly) NSTimeInterval timestamp;
@property(nonatomic,readonly) UIAccelerationValue x;
@property(nonatomic,readonly) UIAccelerationValue y;
@property(nonatomic,readonly) UIAccelerationValue z;
@end
UIKIT_CLASS_AVAILABLE(2_0)
@interface UIAccelerometer : NSObject {
@private
NSTimeInterval _updateInterval;
id <UIAccelerometerDelegate> _delegate;
struct {
unsigned int delegateDidAccelerate:1;
unsigned int reserved:31;
} _accelerometerFlags;
}
+ (UIAccelerometer *)sharedAccelerometer;
@property(nonatomic) NSTimeInterval updateInterval; //May be capped at a minimum interval
@property(nonatomic,assign) id<UIAccelerometerDelegate> delegate;
@end
@protocol UIAccelerometerDelegate<NSObject>
@optional
- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration __OSX_AVAILABLE_BUT_DEPRECATED(__MAC_NA,__MAC_NA,__IPHONE_2_0,__IPHONE_5_0);
@endIf you were given this header file, how would you test this?
How would you test the (any generic method) [NSURL initWithNSString] method?
Where are the stack and heap located? How would you write a c program to tell if the stack frame was growing?
In regular expressions, what is the mean of the "+","*","?" operators?
Suppose you have 100,000 files spread across multiple servers and you wanted to process all of them? How would you do that in Hadoop?
In the Hadoop Hello World Word Count program what are the Map and Reduce functions?
What is the SQL statement to query two tables at once?
How would you kill a process by name in terminal in one line? i.e. NOT kill -9 pid. Follow-up what happens when you type kill processname or kill pid(actual pid)
Suppose you have a Lion class and you implemented a draw() function that draws the entire body of the lion. Now suppose you want to make a Tiger class, and the tiger is like a lion, but it doesn't have a mane and has stripes. How would you do this?
while reading a binary file with over 1 billion unsigned integers, how can you optimize the following code to make it perform better?
int i=0;
long sum=0;
ifstream file("binary.dat", ios::in|ios::binary);
if(file.is_open())
{
while(!file.eof()) {
file.read(reinterpret_cast<char*>(&i), sizeof(unsigned int));
sum += i;
i = 0;
}
}
file.close();
If you want to explain a gambling event, which has winning probability less than 1/2, to a person don't know probability. How will you do?
----(assume your answer is: do that experiment many times)-------
How many times would be enough?
why do we need weak_ptr? give an example by code!
I didn't answer the question well.
I am really confused about weak_ptr. weak_ptr is an observer of shared_ptr, meaning that we always need shared_ptr in order to use weak_ptr. but in cyclic case, we don't use shared_ptr for one of the object, then in this case how can we use weak_ptr without shared_ptr to break cycle?
Find two no’s in a sorted array whose sum =X ?
i gave a solution whose complexity is O(N) .. Anyone with reduced time complexity?
Which one of these is a keyword in C? (a) printf (b) #define (c) sizeof (d) ->
What is true about the value of π – (22/7) where π is the ratio of the circumference of a circle to its diameter in a Euclidean plane? (a) It is 0. (b) The value changes gradually every year as the universe expands. (c) It is close to 0.001. (d) It is close to -0.001
What is the declaration of a function that returns a pointer to a function which has int * argument and return type void? First show how it can be declared without typedef. Next show, how it may be written neatly using typedef.
Why is it important to add a salt to a user's password before storing its digest?
WAP to print the nodes of a tree in a each separate line.
Suppose there is a tree
0
/ | \
1 2 3
/ \ / \ / \
4 6 7 8 9 10
So it should print
1
1 2 3
4 6 7 8 9 10
Give an efficient algorithm to check whether 9*9 matrix is valid sudoku solution or not ?
Given a function, take a number and the bit position and return true if that bit is set to 1 and false otherwise.
It took me a few minutes to think something like this, pasted code is after he corrected me on 2 silly mistakes.
bool ret_result(int number, int pos) {
int k=1;
for(int i=0;i<pos;i++) {
k=k<<1;
}
if(number&k==1) {
return true;
}
else {
return false;
}
}
All the Insert,delete and search complexities for Arrays,HashMaps,Binary trees.
The normal shell script question, give a unix command that takes an input as a pattern and searches all unique numbers in the file
I came up with egrep [ pattern ] im not sure if it was correct syntactically but i explained the logic to him and he said ok, lets move on to the next question -.-
Given an file which consists thousands of lines. each line consists of a string and several integers.
design an algorithm which take input of several integers and print out the string of the line that have most matches.
input file
----------
aa 3 4 10 2
bb 9 14 15 21 3
cc 12 1024 200 3 9 4
----------
examples:
input: 3 4 10
output: aa
input: 12 3 4
output: cc
input: 3 9
output: bb
input: 3 9
output: cc
input: 3 4 12
output: cc
Thanks!
Hashmap vs Arrays ?
Which is better ?
Hashmap worst case search is O(n) same as of arrays which is also O(n) then what is the advantages of hashmap
Given an array find 3 elements such that a[i] < a[j] < a[k] and i < j < k in 0(n) time.
Implement a Queue data structure and provide enQ and deQ functionality where the only data structure you have to use is stack.
WAP to find nth Fibonacci number. After I wrote the code, had to read it out line by line. then she asked follow up questions like why this method, what other ways you can write the algorithm, etc.,
What is a hashMap/ hashTable?
What happens if we have a bad hashing function?
How does java store the hashtable/hashmap?
WAP to count the num of possible hops the bunny can make. conditions are -
- bunnies are positions of bunnies on a number line
- count the number of valid hops
- A bunny at the position 'a' jumps over bunny at position 'b' and lands at the position c, c = 2b-a
- A bunny can only hop over one other bunny, and cannot land on another bunny.
- There are at least two bunnies.
- The bunnies are in sorted array.
- The bunny can hop in both directions.
Simple one to write a program to calculate avg of int array.
An expression consisting of operands and binary operators can be written in Reverse Polish Notation (RPN) by writing both the operands followed by the operator. For example, 3 + (4 * 5) can be written as "3 4 5 * +".
You are given a string consisting of x's and *'s. x represents an operand and * represents a binary operator. It is easy to see that not all such strings represent valid RPN expressions. For example, the "x*x" is not a valid RPN expression, while "xx*" and "xxx**" are valid expressions. What is the minimum number of insert, delete and replace operations needed to convert the given string into a valid RPN expression?
Input: The first line contains the number of test cases T. T test cases follow. Each case contains a string consisting only of characters x and *.
Output: Output T lines, one for each test case containing the least number of operations needed.
Constraints: 1 <= T <= 100 The length of the input string will be at most 100.
Sample Input:
5
x
xx*
xxx**
*xx
xx*xx**
Sample Output:
0
0
0
2
0
Explanation:
For the first three cases, the input expression is already a valid RPN, so the answer is 0. For the fourth case, we can perform one delete, and one insert operation: xx -> xx -> xx
An expression consisting of operands and binary operators can be written in Reverse Polish Notation (RPN) by writing both the operands followed by the operator. For example, 3 + (4 * 5) can be written as "3 4 5 * +".
You are given a string consisting of x's and *'s. x represents an operand and * represents a binary operator. It is easy to see that not all such strings represent valid RPN expressions. For example, the "x*x" is not a valid RPN expression, while "xx*" and "xxx**" are valid expressions. What is the minimum number of insert, delete and replace operations needed to convert the given string into a valid RPN expression?
Input: The first line contains the number of test cases T. T test cases follow. Each case contains a string consisting only of characters x and *.
Output: Output T lines, one for each test case containing the least number of operations needed.
Constraints: 1 <= T <= 100 The length of the input string will be at most 100.
Sample Input:
5
x
xx*
xxx**
*xx
xx*xx**
Sample Output:
0
0
0
2
0
Explanation:
For the first three cases, the input expression is already a valid RPN, so the answer is 0. For the fourth case, we can perform one delete, and one insert operation: xx -> xx -> xx
How can I do arrangements. of numbers... such that each new number formed out of arrangement has at max a difference of 1 from prev maxima.
e.g.
if input is k=1 output will be 1
if k =2 outputs are : 11, 12
2,1 is wrong as left most has to be 1 always.
if k = 3 outputs are: 111,112, 121, 122, 123
if k = 4 : 1111,1112,1121,1122,1123,1212,1211,1213,1223,1221, 1222, 1233, 1234
1423 is wrong diff b/w 1 and 4 is 3.
1243 is wrong diff b/w 2 and 4 is 2....
How I do this using DP? if possible ?
Describe in detail what new operator does, elaborate on memory allocators, kernel free page requests and cascading constructor calls in case of derived classes.
Write a program to return the longest repeating
substring in a string. eg. for "ababab", "abab" is the longest repeating substring.
Ur a given a url in following format:
<protocol>://<host name>:<port>/<filename>
implement a function which takes URL and do following operations:-
1. convert hostname & protocol into lowercase.
2. replace "//" by "/"
3. if host name is no there, add "http://" at the begining of the url.
4. if url contains filename, remove filename from the Url.
write data structure for dictionary.
1. implement function for inserting a word into a dictionary.
2. implement function for lookup in dictionary.
There are M files(>100MB) containing N log entries.
log entry: <customer id, access time>.
We need to merge all M files into 1 file. How can we do this in optimal way. (write algo only).
you are given a url in a format:
<protocol>://<hostname>:<port>/<filename>
eg. http://www.amazon.com/index.html
implement a function which takes url and do following operations on it:-
1. convert protocol & host name to lowercase.
2. If Url don't contain protocol ,then add http:// at the beginning of the url.
3. replace "//" by "/"
4. if Url contain file name, then remove the file name from the Url.
Write data structure for dictionary.?
Implement function for inserting a word into a dictionary .
Implement function for look up in dictionary.
There are M files(>100MB) containing N log entries.
log entry: <customer id, access time>.
We need to merge all M files into 1 file. How can we do this in optimal way. (write algo only).
There are N people in a village.Everybody knows the head of the village.But nobody else knows everybody else,i.e. an ordinary person may know some people but not everybody.Given a function knows(Person p1 ,Person p2) which return true if p1 knows p2.Find who is the head of the village ,preferably in O(N).
There are N people in a village.Everybody knows the head of the village.But nobody else knows everybody else,i.e. an ordinary person may know some people but not everybody.Given a function knows(Person p1 ,Person p2) which return true if p1 knows p2.Find who is the head of the village ,preferably in O(N).
Given a string, find the substring with minimum length from it which contains exactly equal no of characters given in a hashmap which contains key as character and values as count of character needed in substring.
For example:
String str ="abcrefbda";
map = {{"b"=1},{"d"=1"},{"a"=1}};
Output = "bda";
Difference between Java and C++
How to Implement Linkedlist using arrays? Just the fundamentals. The followup question was what are the disadvantages in terms of memory when the array resizes.
Amazon receives marketplace sellers (clients) requests in XML format. Sometimes, the clients software makes mistakes and omit certain nodes starting or ending tags (or both). Amazon, being the earth most customer friendly company, still wants to honor the client’s request by converting this malformed XML to well-formed XML. Given a malformed XML as string, you have to return the structure that the input XML follows .
Following are the assumptions you can make:
1. XML follows the structure below :-
a. Any parent node ( say with tag A ) can have multiple children but only of the same tag ( say B ).
b. A tag can occur only at the exactly one level in the XML Structure ( say tag B can only occur at the level 2)
c. There is single leaf node tag.
2. For a given XML input, it will honor only a unique XML structure.
3. All node tag names are unique.
4. There is a single root node which is always present in the input XML.
Input Format:
Only line in the input contains a malformed string.
Output Format:
Print in a single line, space separated list of tags in the structure. Tags that are more closer to root has to be printed before the ones that are farther.
Sample Input:
<A><B></B><D><C></C></D><B><D></D></B></A>
Sample Output:
A B D C
Explanation:
The actual XML structure is root with tag 'A' . Root has two children each having tag 'B'. Each of the node with tag 'B' has one child with tag 'D' and finally each of the node with tag 'D' has one children with tag 'C'. The well-formed string for this case is "<A><B><D><C></C></D></B><B><D><C></C></D></B><B><D><C></C></D></B></A>" and in the sample input some of the tags were missing.
Constraints: The number of nodes is not more than 10,000. Size of tag string is less than 20.
As a follow up to the Problem "XML Structure", given the input malformed XML String and the XML structure that it needs to follow, you need to find the well-formed XML String. You can assume that malformed XML string does follow the given structure and there is a unique well-formed XML String corresponding to it.
Input Format:
First line of input contains the structure of XML. Next line of input contains the malformed string.
Output Format:
Print in a single line the well-formed XML string.
Sample Input:
A B D C
<A><B></B><D><C></C></D><B><D></D></B></A>
Sample Output:
<A><B><D><C></C></D></B><B><D><C></C></D></B><B><D><C></C></D></B></A>
Note: You can attempt this problem without attempting XML Structure problem first, however you should read the problem XML Structure for proper background in order to solve this.
Constraints: There will be no more than 10,000 nodes.
You received a transmission containing an expression of single digit positive integers (say: 9 *(5 – 4) * 3). However, during transmission all operators and brackets were lost and you only received 9 5 4 3. Given the array of digits, you have to calculate the least positive integer value of the expression that could NOT have been received by you. The binary operators possible are *, +, -, / and brackets possible are ( and ). Note that / is an integer division i.e. 9/5 = 1.
Example: You have received 6,6,4,4. The minimum positive integer that could NOT have been formed is 18. This is because integers less than 18 are formed as below.
1 = 6 /6 + 4-4
2 = 6/6 + 4/4
3 = 6 +( 6/4) -4
4 = (6+6+4) / 4
……..
18 cannot be formed
Input Format:
FIrst line contains an integer N, the number of digits in the array.
Then follow N lines each containing a digit.
Output Format:
Print a single integer which is the required answer.
Sample Input:
4
6
6
4
4
Sample Output:
18
Constraints:
1 <= N <= 10
Note: You need not worry about the precedence of operators as you can impose necessary precedence using brackets at appropriate places.
malloc implementation
malloc allocation & stack allocation compare
Detailed questions on projects
Difference between array and linked list
Im sure everyones heard of this.
Matrix with rows and column sorted. Find a particular element.
I mentioned the O(m+n) solution. He asked to make it better.
Thought for a while, then told him that you start with the last element of the first row and once you find the row which might contain the element, do a binary search on that row (since its sorted).
This further brings down the complexity to O(m+logn).
He said make it even better.
So I said do a binary search on the last column and look for the row where the element in the previous row is smaller and the element in the current row is greater than or equal to the target.
So the complexity becomes O(log m + log n).
He said ok.
When I was about to code this, he said there are two ways to implement it.
1) One you implement the dual binary search method.
2) Make use of the facts that the rows and columns are sorted.
Thought this over for a while and mentioned that instead of doing two binary searches, you can do just one considering the entire matrix as a linear array and doing binary search.
The complexity would be log(m*n)=log(m) + log(n).(Same as the previous optimal solution).
There would be some logic involved in translating the indices to (row,col) pairs. I got this working, but he wanted me to return the (row,col) pair if the element was found or (-1,-1) if not found.
For this he gave me the function signature
void find(int A[][10], int m, int n, int target,int&row, int col)
which is what I couldn't figure out. Here m = number of rows and n=no of cols
Here is the solution I gave
// Initially pass start as 0 and end as m*n when calling function
find(int A[][10],int start,int end,int target,int cols)
{
int mid = (start+end)/2;
if (start > end)
{
element not found;
}
int r = mid/cols;
int c = mid%cols;
if(A[r][c] == target)
{
element found;
}
else if (target>A[r][c])
{
start = mid+1;
find(A[][10],start,end,target,cols);
}
else
{
end = mid-1;
find(A[][10],start,end,target,cols);
}
}Can somebody tell me how i can return the (row,col) pairs (yes! return two values) using the function signature he mentioned.
PS: Thanks for reading the whole post.. I know its kinda long. But I hope it helps someone.
Difference between threads and process.
Simple enough.
write a program which returns the first non repetitive character in the string.
write a program to find whether the string is palindrome or not.
what's the signature of [ ] in std::map? why not const?
what's the advantages of using vector than c array(heap)? what's the difference of the memory models? how is vector more efficient than c array?
0 Answers
Write an efficient code to print pairs of anagrams from a given set of strings.
ex: anna, hjsds, nana, werwe, sads, eerww
Ouput:
anna nana
werwe eerww
Write an efficient code to print pairs of anagrams from a given set of strings.
ex: anna, hjsds, nana, werwe, sads, eerww
Ouput:
anna nana
werwe eerww
which macro is to initilize the *variable in function with variable of arguments ?
in c,if you pass an array as an argument to a function,what actuallay gets passed ?
what is the result of 16>>2 ?
#define square(X) X*X
sq=square(2+3)
what will be the value of 'sq' after the above code is executed ?
#include<stdio.h>
int main()
{
printf("BCA II");
main();
retrun 0;
}
how many times the above program will print "BCA II" ?
void func()
{
int x=0;
static int y=0;
x++;
y++;
printf("x=%d,\t y=%d\n",x,y);
}
void main()
{
func();
func();
}
what will be the output of the above code?
Find the intersection of two linked list given their head pointer.
Constraint: You can only traverse a linked list only once.
write code for following function:
string convert(int n)
{ ... }E.g. input: n = 5
E.g. output: "1,2,3,4,5"
minimize the creation of string objects while coding, and consider that n = 1000000000
Binu is an aspiring pattern-artist. He spends his free time creating patterns using the computer keyboard. One day, he was creating a random pattern using “/”and “\” characters and during the process, realized that his pattern contained open paths and enclosures (see figure alongside). In this figure, Binu has drawn 6 characters (using either “/” or “\”) each in 4 rows on a standard graph paper. He counted two enclosures (marked with dots), the larger one of 16 squares size and the smaller one of 4 squares size. He also noticed several open paths (non-closed spaces) which are not relevant in the context of this problem. Your task is to help Binu by writing a program that counts all the enclosures in a given pattern and find the size of the largest enclosure. For simplicity, we will not dwell into cases where there are enclosures within enclosures (your code doesn’t need to consider such cases). You may note in the figure that each “/” or “\” is equivalent to 2 units in the graph.
Input:-
The input file would contain multiple independent test cases, each test case being a pattern, drawn by Binu. Each test case begins with two integers a and b (1 <= a <= 50, 1 <= b <= 50) where a and b represents the length and breadth of the pattern. The next b lines contain a characters each which are either “/” or “\” (no whitespaces in between). The input ends with a test case having a and b as 0. In the above figure, a = 6, b = 4.
Output:-
For each test case, your code needs to output (on a separate line) two integers x and y (separated by a single whitespace) where x is the total number of enclosures in that pattern and y is the size of the biggest enclosure. In the above figure, the output would be 2 16; meaning, there are 2 enclosures & the size of the largest enclosure is 16 squares. If there are no enclosures in a pattern, you need to output 0 0. If two or more enclosures have the same size (and that happens to be the maximum size), you need to output that size.
EX I/P:
6 4
\//\\/
\///\/
//\\/\
\/\///
3 3
///
\//
\\\
0 0
EX O/P
2 16
0 0
Note:
/\
\/
will have 4 diamond shape squares in it. They have given a image. not able to add it here.
public void myFunction(int n)
{
if (n == 0)
return;
else
{
print(n);
myFunction(n--);
print(n);
}
}
what does it show?
Give an array of integers, which are in repeated format except one integer, write a function to return that integer
ex[2,2,3,3,4,4,4,5,5] = 4
[2,2,2,3,3,3,3,4,4,4] = 3
Return all factorials of given integer. Enhance your approach by avoiding linear traversing.
Calculate number of zeros in a given integer.
What is a hash table , give all collision avoidance techniques
calculate average of the values in a binary tree?
implement two functions that
1. inserts a very large string at any given character index in a given string
eg: if given a string "house" insert a very large string at index 2 after "o", the large string could be 1 GB in size
2. appends a very large string to another string,
which would be your data structure of choice to store such strings,
algorithm should be efficient with time and space constraint to perform any action
given a three character a,b,c.find the total no of N length string formed by there three character.
condition
1. no more than 2 consecutive 'a' appear in string.
2 .only one "b" present in string.
3 no condition on "c".
How to count duplicate words in given paragraph in c.
Example : Ram is a boy.Ram is a Great boy
in this example 2 ram ,boy ,is ,s
You have a point say Point<x,y> get the 10 nearest point to the centre with complexity of 0(1) as you add element.
give an algorithm to generate random numbers between 1 and 2.
IF YOU HAVE GIVEN AN ARRAY CONTAINING CHARACTERS , YOU HAVE TO SEGREGATE ALL NUMRALS , ALL SMALL CHATACTERS(a-z) , all capital characters (A-Z) and all rest all special characters. so basically we need to group these characters in 4 parts.
Write a program to count the permutations of the first n natural numbers: 1,2,3...n where in each permutation a1a2a3...an the ai dijit is less than or greater than all previous digits. For eg: valid permutations for n=4
1234
2341
etc
Queue. Implement a queue
Binary Tree. How will you implement Binary tree
What is Inner Join, Left outer join. What is a view
Write a sql query to select duplicates in a Table.
Celebrity problem:
You have a room with n people. A celebrity walks in. Everyone knows the celebrity, the celebrity knows no one. Non-celebrities may/may not know anyone in the room. Give an algorithm to find the celebrity. Discuss the complexity.
This is a very simple question. But im not sure why the answer is the way it is.
int main()
{
char *c = "abc";
*c = 'd';
printf("%s",c);
return 0;
}
What gets printed?
I said dbc for which he dint say anything and went ahead.
I coded this and found that I my compiler doesn't even give a response. I don't understand, *c sets the value being pointed to 'd' so technically this is legal right?
Can someone pitch in?
amazon-interview-questions 8 Answers
3-way-mergesort : Suppose instead of dividing in half at each step of the mergesort, you divide into thirds, sort each third, and finally combine all of them using a three way merge. What is the overall running time of this algorithm ? (Hint - Note that the merge step can still be implemented in O(n) time.)
n
nlog(n)
n^2(log(n))
n((log(n))^2
You are given functions f and g such that f(n)=O(g(n)). Is f(n)∗log2(f(n)c)=O(g(n)∗log2(g(n))) ? (Here c is some constant >0. You can assume that f and g are always bigger than 1.
Depends on the choice of f and g
True
False
Depends on choice of c
Arrange the following functions in increasing order of growth rate. ie. if g(n) follows f(n) in your list, then f(n) is necessarily O(g(n)).
a)22n
b)2n2
c)n2log(n)
d)n
e)n2n
what is the range of int data type?
what is the maximum number (decimal number) that can be stored using any datatype ?
what does malloc returns ? what happens when ou write:
List* node;
node=malloc(sizeof(node));
where does node points to ?
given a linked list and two integers M and N. Scan the linked list such that you retain M nodes then delete next N nodes and continue the same till the end of linked list.
An infinitely long stream of bits coming one bit at a time. You have to tell (at any point of time), whether the decimal number is divisible by 3 or not .
what does malloc return ?
what happens when you allocate memeory using malloc(sizeof(node)) in your code, where node is a pointer variable of list* node;
An infinitely long stream of bits coming one bit at a time. You have to tell (at any point of time), whether the decimal number is divisible by 3 or not .
find kth maximum element of binary search tree in log(n)
reverse a doubly link list without swapping pointers
Reverse a string in O(n) with recursion
You are at a political convention with n delegates, each one a member of exactly one political
party. It is impossible to tell which political party any delegate belongs to; in particular, you will
be summarily ejected from the convention if you ask. However, you can determine whether any
two delegates belong to the same party or not by introducing them to each other—members of the
same party always greet each other with smiles and friendly handshakes; members of different
parties always greet each other with angry stares and insults.
(a) Suppose a majority (more than half) of the delegates are from the same political party.
Describe an efficient algorithm that identifies a member (anymember) of the majority party.
MS written test:
Given a list of words and a dictionary with many words. The dictionary may or may not include the the given list of words.
From the given list of words,you need to print only those words which are present in dictionary.
Mention time complexity.
MS written test:
STRINGZ = STRINGX + STRINGY.charAt(index) ,
How can it be done using C language.
Also, I want to add a character in each function call.
e.g.
FUNC(mainstr,"");
FUNC(char *mainstr, char *current)
{
if(index==strlen(mainstr))
print("%s",current);
else
for(int i=0; i<strlen(mainstr) ; i++)
{
FUNC(mainstr, current+mainstr.charAt(i))
}
}
//replace current+mainstr.charAt(i) with C functions and code ..
Given a number (lets say 10 digit) - print all possible words that can be made from a phone pad. Remember that number n can vary. Also some numbers like 2 have ABC (only three alphabets) while 7 can have (PQRS) 4 alphabets. Your algorithm should acommodate all these.
(Kids do the above part - it is a classic programming interviews exposed question).
I used recursion to start with.
Space complexity is O(1) (not considering stack) - as we are just printing.
Worst case time complexity is (4^n). - all numbers are 7.
The trick question was - how much STACK space will recursive prog require? -- I bombed this trick ques. and got a reject.
hw to find least 1 million numbers form a set of a billions numbers most optimally ? if we can use heap in this if yes kindly explain step by step
int i=10,j=20;
int *p=&i;
int *q=&j;
int c=p-q;
what is the value of c and explain the output.
Giver two sorted arrays a[] and b[].
Merge them a[] in b[] in sorted order. Assume b[] has the extra space to accommodate a[]
Detect if there is a cycle in a directory structure.
For ex- (Folder - Caps, Files - small)
A- > B,C,a
B->C,D,b,c
D-> A,d
So there is a cycle -> A-B-C-D-A
Two linked lists meet at a node and then continue as a single list. Find this node most effectively
How do you find the middle element of a singly linked list in the most effective manner?
design a server architecture for serving Google maps images
Given a list of strings, Print all possible letter strings in sorted order.
Remember that the characters in each string are sorted.
Sample I/P:
YZ
ABCD
DEF
O/P:
ADY
ADZ
AEY
AEZ
AFY
AFZ
BDY
BDZ
BEY
BEZ
BFY
BFZ
CDY
CDZ
CEY
CEZ
CFY
CFZ
Given some words(written in lexical order) of some unknown language...You have to find lexical ordering of all the alphabets...
Like in english lexical ordering is A B C...Z
How to find a largest palindrome from a given string? Write code....
You r given a matrix of 0s nd 1s. WAP that check if an element is 0 or not and places zeros to all the col and row of that element.
eg: i/p: 1 1 1 1 o/p : 1 1 0 1
1 1 0 1 0 0 0 0
1 1 1 1 1 1 0 1
1 1 1 1 1 1 0 1
How to compute A^n where n<1 million
Write code...
How to compute all possible solution of A^3+B^3=C^3, where A,B,C belongs to (0 to N)?
Write code...
How will you write a randam function?
"you have to design a class "Deckofcards"...with 2 operations: 1:Shuffle 2:Pick"
Pick would pick a randam card from the deck and Shuffle will shuffle the cards and give you bac the deck of cards.
I answered with 2 options 1.LinkedList 2:Array...thn thr ws a discussion for arnd 10 mins over the soln...
What is the diameter of a tree?
I answered...
then he told me to write the complete code...
You r given an sorted bt rotated array of integer like: 6 7 8 1 2 3 4 5
You have to search an element...
I answered vd an O(logn) solution...
then he told me to write the code...
WAP to find maximum sum sub-matrix from a give matrix.
Given two trees T1 and T2. WAP to check whether T1 is a subtree of T2 or T2 is a subtree of T1
WAP to merge two linked lists like:
list1: 1->2->3->4
list2: 5->6->7
o/p list: 1->5->2->6->3->7->4
Find the seed of a number.
Eg : 1716 = 143*1*4*3 =1716 so 143 is the seed of 1716. find all possible seed for a given number.
Given a binary tree and 2 values. Write a function to find the 1st common ancestor in the binary tree.
The method I have used is that the common ancestor is the one who would have value between the given 2 values. So for example if the values are 3 and 10. so the common ancestor would be a node with value greater than 3 and less than 10.
here is my code.
public Node getCommonAncestor(Node root,int a, int b)
{
if((root.value>a && root.value<b) || (root.value<a&&root.value>b))
{
if(checkvalue(root,a) && checkvalue(root,b))
{
return root;
}
else
{
return null;
}
}
else if(root.value>a && root.value>b)
{
if(root.left != null)
{
return getCommonAncestor(root.left,a,b)
}
else
{
return null;
}
}
else
{
if(root.right != null)
{
return getCommonAncestor(root.right,a,b)
}
else
{
return null;
}
}
}
public boolean checkvalue(Node root,int a)
{
if(check.value == a)
{
return true;
}
else if(check.value>a)
{
if(check.left != null)
{
return checkvalue(check.left,a)
}
else
{
return false;
}
}
else
{
if(check.right != null)
{
return checkvalue(check.right,a)
}
else
{
return false;
}
}
}
class Node
{
int value;
Node left;
Node right;
}Can you suggest whether I am right or not?
Given a binary tree and 2 values. Write a function to find the 1st ancestor of the binary tree.
There are two arrays of length 100 each. Each of these has initially n (n<=100)
elements. First array contains names and the second array contains numbers
such that ith name in array1 corresponds to ith number in array2.
Write a program which asks the user to enter a name, finds it in array1,
a. if it exists, then print the corresponding number in array2,
b. else ask the user to input its associated number and add the number and
name to array2 and array1 respectively, and update the size of list.
create an Objective-C class, with accompanying header file. The class will represent a book, and should have a title, author, and a year of publication. Be sure to provide a designated initializer and accessors for these properties.
You may optionally provide a small main() function that demonstrates its use.
what is normalization
explain list, set and map
A singly linked list has integer as data in each node. Write a function to delete a node from the list given an integer as argument. (Assume all the nodes have unique integers)
Given a Binary tree , you need to traverse and only print all nodes on given level L.
Write a function which sets the bits in an integer when start bit position and end bit positions are passed as argument.
For eg, if I call function setbit(2,4) , it should return 14. (1110)
least significant bit on 1st position and so on..
Write a function to sort the linked list given the head as parameter. Do not use extra memory. You have to sort it in place. Time complexity is secondary. (He told me that he wants to see how fast I can code with any of of the solutions)
If I send a ping request from one host to another, what exactly happens in the network. Explain in detail
Write an algorithm to find F(n) the number of bits set to 1, in all numbers from 1 to n for any given value of n.
Complexity should be O(log n)
For example:
1: 001
2: 010
3: 011
4: 100
5: 101
6: 110
So
F(1) = 1,
F(2) = F(1) + 1 = 2,
F(3) = F(2) + 2 = 4,
F(4) = F(3) + 1 = 5,
etc.
I can only design an O(n) algorithm.
You are working on an exam and the question is smudged and you can’t see the question. Based on the answers only, what is the answer? I am not certain if I remember the question exactly, but it is some variation of these statements .
A) All of the below
B) None of the below
C) Some of the above
D )None of the above
E )None of the above
You are given a 2D array of characters and a character pattern. WAP to find if pattern is present in 2D array. Pattern can be in any way (all 8 neighbors to be considered) but you can’t use same character twice while matching. Return 1 if match is found, 0 if not.
eg :
Matrix
{'A','C','P','R','C'},
{'X','S','O','P','C'},
{'V','O','V','N','I'},
{'W','G','F','M','N'},
{'Q','A','T','I','T'}
And pattern is microsoft.
It's funny when google looks for pattern of microsoft ;)
All the shoes are Reebok with the exception of two shoes , All the shoes are Nike with the exception on two shoes. All the shoes are Fubu with the exception of two shoes. How many shoes are there ?
Given the start and an ending integer as user input, generate all integers with the following property.
Example : 123 , 1+2 = 3 , valid number
121224 12+12 = 24 , valid number
1235 1+2 = 3 , 2+3 = 5 , valid number
125 1+2 <5 , invalid number
Write a program to generate all palindrome dates by taking the beginning and the ending dates as an input from the user. The format of the date is given as MMDDYYYY.
How many spaces does the following struct take on a 32-bit computer?
struct s{
char c;
int i;
double d;
void *p;
int a[0];
}
Given a linked list of integers, delete all the nodes from the linked list which data value equals to a given value.
void delete(Node **l, int target);
write a function to determine if a string contains a repeated sequence
write a fucntion to delete a node from a linked list if pointer to head and node no. is given
write a function to rotate an m x n array by 90 degrees
How can we avoid a stack overflow ?
The problem is like this. Lets say I have a method A() invoked from main(). Now A() invokes B(), B() inturn invokes C() ... keep going...
so the current process stack will have limited capacity to accomodate all the activation frames that are being created dynamically when each new method is invoked.
so if this continues, at one point of time, stack will exhaust. so whats the method to handle this.
The very simple example can be:
void main (){
main();
return 0;
}
if you run this, we can see the error as run time error for stack overflow. in such scenario whats the optimal way to deal with it?
How to add (to find sum) a1+a2+a3+.....an ,where a1,a2,...an are integers but they are large enough (so they can't handle by any primitive data type in C).
create an Objective-C class, with accompanying header file. The class will represent a book, and should have a title, author, and a year of publication. Be sure to provide a designated initializer and accessors for these properties.
You may optionally provide a small main() function that demonstrates its use.
There are 1000 files located in a Unix directory tree under /repository. You are asked to provide a list of every filename that contains an IP address. How would you solve this problem? Provide a working example.
there is n node graph, each node having only one root. All nodes are labeled in a random order from int 0 to n-1
the graph is represented in a array format such that the value in the array at index equal to child node label is root node label.
For root assume the value is -1.
Ex.
3
4 1 2
0 5the array is
value : 1, 3, 3, -1, 3, 1
Index : 0, 1, 2, 3, 4, 5
Find the hight of graph. I have given an answer in O(n^2)
follow up question, if you dont have any restiction on space reduced the time complexity.
Given a 3D space with a billion points. Give a million points which are closest (in distance) to a given point.
Given two lists of strings return a list of strings that is an intersection of both of the lists.
Analyze running time and space complexity.
Give Test Case scenarios.
What is a queue, advantages, disadvantages
What is a Stack, what are its advantages, disadvantages.
What is finally in java, and why is it used.
Exceptions in Java, checked/unchecked and how are they handled
What is an abstract class and how is it different from a normal class, give a scenario where you would use one over the another
Write a Program
You have an array that stores million integers. you replace one integer of the array. How will you find that integer. Array is not sorted. Time complexity should be as small as possible.
Write a Program
Reverse a String. Length of String is very long. Do not use in-built reverse method. Reversal method should be time efficient. Calculate the complexity.
Write a Program
You will create an employee class with the following properties:ID (int), FName(string), LName(string). (Functionality) to track an employee's manager and subordinates. method that displays the names of all subordinates for a given employee.
What is an abstract class and how is it different from a normal class, give a scenario where you would use one over the another
Given an integer n, compute 2 integers x, y satisfying: n<=x*y<=n+2; |x-y| is minimal.
Given two binary trees T1 and T2 which store character data, duplicates are allowed. Devise an algorithm to decide whether T2 is a subtree of T1. T1 has millions of nodes and T2 has hundreds of nodes.
There is a monkey which can walk around on a planar grid. The monkey can move one space at a time left, right, up or down. That is, from (x, y) the monkey can go to (x+1, y), (x-1, y), (x, y+1), and (x, y-1). Points where the sum of the digits of the absolute value of the x coordinate plus the sum of the digits of the absolute value of the y coordinate are lesser than or equal to 19 are accessible to the monkey. For example, the point (59, 79) is inaccessible because 5 + 9 + 7 + 9 = 30, which is greater than 19. Another example: the point (-5, -7) is accessible because abs(-5) + abs(-7) = 5 + 7 = 12, which is less than 19. How many points can the monkey access if it starts at (0, 0), including (0, 0) itself? There is no input for this program.
Print out the how many points can the monkey access. (The number should be printed as an integer whole number eg. if the answer is 10 (its not !!), print out 10, not 10.0 or 10.00 etc)
F2F Round4 Q2
Write code to find Nth last node in a linked list.
F2F Round4 Q1
Given two strings str1 and str2, write code to find out if all non-unique elements in str2 are in str1?
F2F Round3 Q3
Given a binary tree build a vertical sum array.
F2F Round3 Q2
Design a chess game.
F2F Round3 Computer Fundamentals
What is the difference between a 32bit and 64processor?
What is the difference between a 1.8Ghz processor and a 2.3GHz processor?
Invent your own tables and write a query to get top 10 mobile numbers with the highest 3G data usage.
F2F Round2 Q3
Given a node in a binary tree, how will you find out if left and right subtrees are mirror images of each other?
F2F Round2 Q2
Given an array A, build another array B in which each element is the product of all elements in A other than the element at the same position. Write code that does this with and without division.
F2F Round2 Q2
Given an unsorted array and a number N, build pairs using the numbers in the array that add up to N.
F2F Round1 Q4
Find the biggest BST in a given binary tree.
F2F Round1 Q3
How will you find out if a given binary tree is a BST?
F2F Round1 Q2
Design a hash table. How do you address collisions?
F2F Round1 Q1
Write code that defines a data structure to perform these operations in an optimal way:
InsertAtTail
DeleteNodeAtPosition
GetTail
Written test Q2
Given a binary tree and a number N, print all paths that start from root and add up to N.
Written test Q1
Find the position of first '1' in a sorted array that contains only 0-s and 1-s.
There is an array of numbers
>> the adjoining elements of array can be either -1 or +1.
>> if a value is given then what is good way to find it's position in the array.
How we perform counting inversion(means if(i<j) then a[i]>a[j]) using unix commands ?
Given:text file containg 1,00,000 distinct numbers from (1-1,00,000) randomly.
suppose we are getting an infinite binary stream of characters then after any point of time you need to print whether the no is divisible by 3 or not, how will you do that?
Say there is a string hllsacefgdbdfdfdffd
You need to find the biggest string that has all consecutive characters
Conditions
consecutive string might have jungled words i.e acb is also continous or bcad is also continuous
How to find min-weight (coin) in a given set of '10' distinct weights (coins) in minimum number of weighing's if provided with a balance. (no labels shown on coin resembling the weight). Generalize for 'n' distinct weights.
Lambda expression .Where() is more efficient than foreach loop?
Lambda expression .Where() is more efficient than foreach loop?
Lambda expression .Where() is more efficient than foreach loop?
Lambda expression .Where() is more efficient than foreach loop?
In a dial pad(similar to phone dial pad) where if 2 corresponds to 'abc' and 3 corresponds to 'def' etc. Write a program to form all possible and meaningful words for the given number.
Example:
if 2 is pressed possible words are a,b,c. But 'a' is only meaningful word. Hence print 'a' and
if 23 is pressed. The possible words are going to be ad,ae,af,bd,be,bf,cd,ce,cf. 'be' is the only meaningful word. So, print 'be'.
We are given access to a dictionary.
(Edited now)
Why do you need Synchronization and how it works? Working of Implicit and explicit wait() and notify
working of TCP/IP proctocol
Count number of higher bits(1) in an integer alongwith its complexity? improvise it
static synchronized method 1()
{
counter++;
}
synchronized method 2()
{
counter++;
}
use only one counter variable to count the number of method calls to method 1 and method 2?
Given a binary tree which is huge and can not be placed in memory, how do you check if the tree is a mirror image.
Given a book containing 100's of words., If a word is repeated, delete it. Process such that there are no repetitive words.
Given an ebay site model., you have to deal with auctioning of a particular item. Design the billing & auctioning system of the same.
There is a sequence {a1, a2, a3, a4, ..... aN}. A run is the maximal strictly increasing or strictly decreasing continuous part of the sequence. Eg. If we have a sequence {1,2,3,4,7,6,5,2,3,4,1,2} We have 5 possible runs {1,2,3,4,7}, {7,6,5,2}, {2,3,4}, {4,1} and {1,2}.
Given four numbers N, M, K, L. Count the number of possible sequences of N numbers that has exactly M runs, each of the number in the sequence is less than or equal to K and difference between the adjacent numbers is less than equal to L.
Arrange the following functions in increasing order of growth rate. ie. if g(n) follows f(n) in your list, then f(n) is necessarily O(g(n)).
a)2^log(n)
b)2^(2^log(n))
c)n^(5/2)
d)2^(n^2)
e)(n^2)log(n)
3-way-mergesort : Suppose instead of dividing in half at each step of the mergesort, you divide into thirds, sort each third, and finally combine all of them using a three way merge. What is the overall running time of this algorithm ? (Hint - Note that the merge step can still be implemented in O(n) time.)
n
nlog(n)
n^2(log(n))
n((log(n))^2)
k-way-mergesort. Suppose you are given k sorted arrays, each with n elements, and you want to combine them into a single array of kn elements. Consider the following approach. Using the merge subroutine in which you merge the first 2 arrays, then merge the 3rd given array with this merged version of the first two arrays, and so on until you merge in the final (kth) input array. What is the time taken for this strategy, as a function of k and n ? (Optional: can you think of a faster way to do the k-way merge procedure ?)
θ(n^2(k))
θ(n(k^2))
θ(nk)
θ(nlog(k))
Assume again two (positive) functions f and g such that f(n)=O(g(n)). Is 2f(n)=O(2g(n)) ? (Multiple answers may be correct.)
1.Never
2.Sometimes
3.Yes if f(n)≤g(n) for all sufficiently large n
4.Always
You are given functions f and g such that f(n)=O(g(n)). Is f(n)*log2(f(n)c)=O(g(n)*log2(g(n))) ? (Here c is some constant >0. You can assume that f and g are always bigger than 1.
1.Depends on the choice of f and g
2.True
3.False
4.Depends on choice of c
Given an unsorted integer array, place all zeros to the end of the array without changing the sequence of non-zero elements. (i.e. [1,3,0,8,12, 0, 4, 0,7] --> [1,3,8,12,4,7,0,0,0])
given a random array, find all the pairs that sum up to a certain value
convert decimal to binary
how TCP/UDP sockets work
Given a program on fork() system call.
#include <stdio.h>
#include <unistd.h>
int main()
{
fork();
fork() && fork() || fork();
fork();
printf("forked\n");
return 0;
}
How many processes will be spawned after executing the above program?
Given the following code snippet:
class A {
public:
virtual void foo() = 0;
}
class B : public A {
void foo(){};
}
Create a diagram displaying the virtual table mechanism
Given the following definition:
class C{};
How much space gets allocated?
What methods get created?
Given the following definition:
class C{};
How much space gets allocated?
What methods get created?
Given a string "HELLOWORLD" .now you have to write a code to change this string into its ASCII value equivalent .
For example the given string will have its Ascii equivalent string as "72697676798779827668".
The solution should be an inplace algorithm.
1. There is a web URL which contains %20 in place of space, how will your replace every %20 with space?
2. Let's say we have a file on the disk which contains millions of such URL, how will you replace all %20 with space?
3. Let's say, on the file there are only 5% URL which contains this %20, how will your replace with space in most efficient way?
Can you give the syntax to print the date time in C#
General question: If you are provided with 8 balls with one among them heavier than remaining . You have a weighing balance. in how many measures can u identify the heavier ball.
you have a 5 liter and a 3 liter jars. You can use any amount of water. Shouldnt use any other jars or containers. How can you get exact 4 liters of water?
Reverse a vector or array...
Reverse the left and right sub-tree of a binary tree:
for example,
I/P:
0 - root
1 - left child of root
2- right child of root
3- left child of node 2
O/P:
0- root
1 - right child of root
2- left child of root
3- right child of node 2
Class diagram of a system to implement Blackjack
Class diagram of a parking lot ...
Do in-order traversal of tree without using recursion .
Given coins of denomination 4, 5 and 7. How can you make up 13 ?
Find the longest palindrome in a input string.
Example - aaabbaaaccdeqjncsdddmmmkkkmmmddd
Answer - dddmmmkkkmmmddd
How do you find million smallest numbers from a file that contains billions of numbers ?
Whether a given BT is a BST or not.
Implementation of finding all the occurrence of a pattern in given text and then replacing it with some other string.
How will you convert a BST to a Sorted doubly LL.
Process name is VistaarAddUser.sh, but pgrep command doesnt prints the fullname while listing[if path of process is too long],
example
pgrep -lfu $UID|grep 17882
results in,
17882 bash +x /data/rdg2/Vistaar/Common/ToolKit/../../Analytics/ToolKit/bin/VistaarAd
how do u print the full name with path of process using pgrep itself
How will you count the number of students in a classroom in quickest possible manner.
Design a data cache.
Given two arrays which represent numbers. Write a function to add them.
Given a set of non overlapping intervals
Example 1 :(1,4) (6,10) (14, 19) and another interval (13, 17) merge them as (1,4) (6,10) (13,19)
Example 2: (1,5) (6, 15) (20, 21) (23, 26) (27, 30) (35, 40)
New interval (14, 33)
Output should be
(1,5) (6, 33) (35, 40)
This is because the new interval overlaps with (6, 15) (20, 21) (23, 26) (27, 30)
Write an Algorithm and then code for N Queens problem. If there is no solution print "No Solution" or else print the board giving out positions of Queens on the board
Given a binary tree with each node has count (no. of children + 1). Write an inorder traversal to find the ith node in O(lgn).
Node * ithNode(Node *root, int i)
{
// return ith node in Inorder traversal.
}what bugs could make input same but output different in your code
The file(Text file) contains all the 100,000 integers between 1 and 100,000 (including both) in some random order( no integer is repeated).
Your task is to find the number of inversions in the file given (every row has a single integer between 1 and 100,000). Assume your array is from 1 to 100,000 and ith row of the file gives you the ith entry of the array
as an example:
text file(test.txt):
2342
1233
8278
.
.
.
.
.
.
.
Given a Binary Search tree with nodes with unique integers, and given an integer K, find the kth maximum element from the BST.
There is a matrix, m x n. Several groups of people locate at some certain spots. In the following example, there are three groups and the number 4 indicates there are four people in this group. Now we want to find a meeting point in the matrix so that the cost of all groups moving to that point is the minimum. As for how to compute the cost of moving one group to another point, please see the following example.
Group1: (0, 1), 4
Group2: (1, 3), 3
Group3: (2, 0), 5
. 4 . .
. . . 3
5 . . .
If all of these three groups moving to (1, 1), the cost is: 4*((1-0)+(1-1)) + 5*((2-1)+(1-0))+3*((1-1)+(3-1))
My idea is :
Firstly, this two dimensional problem can be reduced to two one dimensional problem. In the one dimensional problem, I can prove that the best spot must be one of these groups. In this way, I can give a O(G^2) algorithm.(G is the number of group).
Use iterator's example for illustration:
{(-100,0,100),(100,0,100),(0,1,1)},(x,y,population)
for x, {(-100,100),(100,100),(0,1)}, 0 is the best.
for y, {(0,100),(0,100),(1,1)}, 0 is the best.
So it's (0, 0)
Is there any better solution for this problem.
Thanks,
Find all the possible passwords, given the length of the password and that it is a well ordered number (159 is well-ordered as 1<5<9)
Given two strings, you need to transpose the first string to the second string by means of only swaps between 2 consecutive characters in the first string. This must be performed by doing a series of these swaps in order to get the second string
Verify if the given password is valid/invalid;
1. must be 5-12 characters long
2. must contain atleast one number and one lowercase character
3. a sequence must not be followed by the same sequence (like 123123qs is invalid, 123qs123 is valid)
Verify if the given password is valid/invalid;
1. must be 5-12 characters long
2. must contain atleast one number and one lowercase character
3. a sequence must not be followed by the same sequence (like 123123qs is invalid, 123qs123 is valid)
You are a hacker and need to find possible passwords given the length of the password and that it is a well-ordered number (eg., 123 is well-ordered as 1<2<3 and 213 is not well-ordered as 2<1<3 is NOT true)
Take a series of integers as input till a zero is entered. Among these given integers, find the maximum of the odd numbers and the minimum of the even integers (not including zero) and print them.
find second largest element in an array in O(n) and in single pass.
Build a dictionary of english words.... you can use any daya strcuture u want?
Design an operating system
Targeted user-> novice users
cost should be minimum.
Design an operating system
Targeted user-> novice users
cost should be minimum.
if a web and a standalone system is developed under the condition like constant no of user for both appliction, same hardware and network configuration. which one will be better and why?
Something that web browser can't do?
design a furniture module, a furniture could be a couch, chair, etc. each furniture could contain multiple materials, wood, steel, etc.
Push all the zero's of a given array to the end of the array. In place only. Ex 1,2,0,4,0,0,8 becomes 1,2,4,8,0,0,0
Given a Relation Person(id,name,momid,dadid)
Return all siblings (ie those with common momid,dadid)
eg 1,2
Write a Program to fill empty cell of a Partially filled MxM Crossword Puzzle to form a valid English words. So the cells initially will be either empty , filled or blocked(cannot be filled). You have access to English Dictionary.
Make a class design for library maintenance. Library can have books, magazine, CDs and DVDs. Any member can checkout from library.
Given a 2D array, all rows and all columns sorted. Find an integer x from the 2D array.
Given 2 Arrays A and B, find the intersection of two arrays. Initially without using any other data structure. Later with using additional data structure.
Find the no which is most repeated in an array and its frequency in O(n)
can operator overloading be implemented in java if yes how?
Is is possible to write a program to print number 1 to 100 wihout using loop. if yes how many way and how?
Spiral traversal of an array.
How many ways two variables can be swapped without using third variable?
3. Data structures. BST, Hash Maps their complexities,
4. Write Code: Find first unique character in an array.
2. Stack vs Heap memory allocation.
4. Write Code: Count number of set bits in an Integer
3. Given a spreadhseet, what data structure you will use to store it. What will you use for dynamic updation of of Spreadsheet formulas.
2. What is difference between overloading and overriding
Write Code: Find an integer array's maximum value. Trace code. Use Try/catch instead of return.
Write a program about temperature measurement. Which should has following keys:
1. Divide the program into different component, better use MVC pattern ( like BusinessLogic Layer, DataAccessLayer, ValidationLayer, GUI Layer)
2. Use Spring.Net for DI.
3. Use NHibernate for ORM & NUnit for test.
System Test: Write a program for searching books by Author name.
1. Develop 3-Tire Architecture. ( GUI Layer, Business Layer, DataAccess layer / DTO)
2. Good to use DI.
3. Show result in Grid and add functionality sorting & Paging.
What is loose coupling & Abstraction ( explain in terms of interface)?
Advantage of Interface?
In .NET framework, execution/build plan when module written in different language?
Difference between Interface & Abstract?
You will find an incomplete class that represents a bounded queue BoundedQueue<T>. A main function is provided that tests the creation and usage of an instance of the BoundedQueue<T>. Implement the required functions such that the class compiles cleanly, the program runs, and all of the tests pass. Do not use any other classes or packages.
create a database schema for...
an application that tracks a bunch of users. the application has a list of races and users can sign up to run for races.
the application also keeps track of if the user has completed their race
give me queries for the following use cases:
1. all the users in the app
2. all the races that a user has signed up for
3. all the races that a user has finished racing
4. all the races that a has signed up for but not raced (meaning they signed up for a race but the race is over and they didn't run in it)
5. find the races that any two users share
you have a book with all the pages ripped out and scattered. The pages are numbered from 1 - n. One of the pages is missing. Write a function that will find the missing page
For String Reversal... how I address the space between the words in a sentence..where in it should be
?
Not necessary inplace..any method is fine.
olleh dlrow
Given N pair of parenthesis. Write an algorithm which would print out all possible permutations possible with those parenthesis given that parenthesis are in correct order (i.e. every open parenthesis is matched with closed parenthesis)
For .e.g. .. N =3 should give:
()()()
(()())
()(())
(())()
((()))
Predict the out put of the following code
#include<stdio.h>
int g = 0;
int Add(int i)
{
static int s=0;
s =s+i;
g=g+i;
return s;
}
int main()
{
int s=0;int g=0,j;
for(int i=1;i<=11;i++)
{ g=0;s=0;
j = add(i);
}
printf("%d,%d",j,g);
return 0;
}Predict the output
Given an Array With random 0s and non 0 numbers, shift all the 0s to the beginning and non 0s to the rear.
Eg: 1,9,8,4,0,0,2,7,0,6,0
Out put 0,0,0,0,1,9,8,4,2,7,6
i.e order of numbers not to change. Do it in place
You are given 2 dice. Both are fair. One of the dice has no numbers printed on it. You have to label the unmarked dice such that when both the dice are thrown, the sum on the faces is evenly distributed between 1 and 12.
Given an array. Find pairs of numbers that add up to a given value 'x'. with time complexity less than O(n2) and use no additional space.
1. Time complexities of Hash table, Array, Linked list
2. I need a fully functional hash table with time complexity for search O(n). How can I achieve this?
Immutable Object in Java?
Difference between Linked List and Array List
Given a tree, write algo to verify whether it is a BST or not?
Find the maximum number in the array and also the frequency of that number in O(n).
Write a function f(n) which computes the number of scoring sequences that add up to score n.
Design a modified stack that in addition to Push and Pop can also provide minimum element present in the stack via Min function.
Design a hash table that is thread safe. That is it can support concurrent reads but protects on write.
Design a collaborative text editor where each participant has infinite undo/redo. Consider the scenario where a user goes offline and then comes online and tries to undo/redo.
Given a sorted array that is sorted by rotated, find a given number. For example take an array: 1 3 8 10 12 56 and rotate it so you have 10 12 56 1 3 8 and then find a candidate e.g. 3 in it.
Given a string representing sorted numbers with spaces print the count of each number. For example if the input string is: "1 1 2 3 4 4" then you should print 1:2, 2:1, 3:1, 4:2
Then the question was modified so there could be invalid number in the string which must be skipped.
Then an added requirement to handle hex numbers in the string.
Given a string representing roman numeral, find and return its numeric value. e.g. XXIV = 24 and so on.
Write a function convert a integer from 0 to 1000 to Roman numerals.
1: I 5: V 10: X 50: L 100: C 500: D 1000: M
Test Cases:
XI 11, IX 9, XXX 30, DC 600, CM 900, XCVIII 98
Write a function convert a string to an integer. example convert String "1750" to int 1750. Using Java, not allow use the default function
A special tree node has one more pointer all initialized to NULL. write a program so that this new pointer will point to next node of same level.
Suppose you have given a 10 digit mobile number (9903457235). Each digit in the number have 3 letters in mobile keypad. find/print all words which can be created by corresponding letter against digit given.. Total 3^10 words, I need complete recursive function.
program to find equivalence of two unsorted arrays
program to convert digit into words in c programming
Goal:
Write a function get_related_pins that takes a pin_id and returns a list of related pin_ids. Note that doing a good job on this challenge is as much about setting up good data structures and decomposing code cleanly as about clever data mining techniques, because setting up a good framework for iterating gets you further in the long run.
Data:
board_json.txt and pin_json.txt are text files of JSON-encoded dictionaries of board and pin object data, respectively. There is data for ~300k pins and ~10k boards, with possible duplicates.
Each board JSON dict contains the fields id, user_id, username, name, slug, description, and category (which may be null, but if not, is one of a fixed set of categories). Each pin JSON dict contains the fields id, board_id, user_id, img_url, is_repin, is_video, source, and link.
To get the data into a format that is easy to work with, consider using a lightweight database system like SQLite.
We want you to write a more intelligent web scraper that will help us grab some
of the following information for sites of your choice:
Prices
Number of Items Available
Seller Information
Tags
Product Rating
Product Details
Product Title
This could work on sites such as Etsy, Amazon, Gap, or other sites of your choice.
Your Code:
Please write a small application that can read a csv of urls and images from a file.
For each url and image link it will download the image into a sub directory and store
its own json blob file of information for the urls. The schema is up to you, but it should
try to be as consistent for different sites as possible
Given an array, write a function to return the kth largest number in the array. Should done in O(n) time complexity.
WCF Implementation and Testing ?
Write performance test plans ?
How would you Develop Performance test cases across Lync features, Execute perf memory testing for eg: Lync
Execute perf time testing for Lync etc
Find 1st non-repeating char in string ?
Given a StackA, & an additional StackB implement PushBottom() and PopBottom() ?
Given an array of integers, find second largest element in an array.
Whats DLL and Net Framework how both are different..?
Find all Subsets that sum upto 10. example
int [] arr ={1,2,3,4,5,6}
Subsets are :
4,5,1
4,6
2,3,5 etc.
Any Suggestions ?
2. how we can modify the default behaviour of setsockopt() parameters
1. describe the steps to add a new global sysctl() or fnctl() paramater.
You have a binary tree. Print node values starting from the root going level by level, i.e. first line has root node's value, second line has two child node's values, third line - left and right child nodes values of the root's left child then left and right child nodes values of the root's right child, and so on.
Five people are to be seated randomly around a circular table. What is the probability of two of them sitting next to each other?
Write a function to merge 2 sorted lists into another sorted list without using extra allocation for new list
They gave me some more code. It was building suffix trees. There was a print function there. He asked me the output of the function which was traversing the suffix tree with given inputs and concatenating the output.
They gave me some code. Asked to find out what it was doing. It was a IsPalindrome function. He asked me how would I improve the code. Given function was recursive. I suggested iterative approach. Also pointed out couple of null checks missing. He seemed to be happy with it.
Let's say you have a simple function (fibonacci/factorial) that you need to run constantly. The largest number that you will receive as input will be 1,000. How can you improve the performance of this function call?
I said not use recursion and cache the results using a data structure (i.e. a Map)
What else could you do to improve the performance?
Why an abstract class can not be instantiated ?
Given a set of points A [A1,A2,...,An] in a XY plane and given another point B, find the kth distant point in set A from B. example: 1st point would be the one at a shortest distance from B and so on. We need to find Kth.
I gave an alogorithm to calculate the distance of point B from every point in set A and then sort this result and return kth (complexity = O(n) +O(nlogn) (for sort nlogn). But I was asked to improve the complexity.
Can someone please help me with a solution with better complexity.
code for MS Paint program. N*N pixels area. given pixel and color, change color in pixel to desired color and if adjacent pixels are of same color change them too. efficient algorithm with place and time complexity
Write a C/C++ program that connects to a MySQL server and displays the global TIMEZONE.
How many comparisons are required to sort an array of length 5 if a straight selection sort is used and the array is already sorted in the opposite order?
Given a binary tree, every node has a int value, return the root node of subtree with the largest sum up value. Java is more preferable. Caution: the return should be a node, not a integer!
Write Program to find longest common contiguous intersection from 2 lists provided to the function.
Example: list1: abcrfghwetf
list2: abrfghwwetxyab
Longest common intersection here is: fghw
Need Effecient Algorithm to implement this in Java or C, not using arrays.
To Check the given linked list is palindrome or not?
Given you have an array A[1..n] of size n, it contains elements from the set {1..n}. However, two of the elements are missing, (and perhaps two of the array elements are repeated). Find the missing elements.
Eg if n=5, A may be A[5] = {1,2,1,3,2}; and so the missing elements are {4,5}
The interviewer was looking for less than o(n) solutions.
Hash map,bit vector or traversal over the array weren't accepted.
Optimized solutions please
when key values are reals a similar data representation might be produced by using a hashing function with
a. mod
b. div
c. trunc
d. logN
Ans-->? Why..?
Decimal number system - { 3 }.i.e a decimal number system without 3.
Find all such number in a matrix if maximum of the row and minimum of the column is same number.
write a program to print the given string as alphabets in order next integres with sum next special characters
example: CAE2W3@D# as input and output should be
ACDEW5@#
write a program to print checksum for given number
by taking last digit sapeate and if sum of squares of remaining numbers are equal to previous last number then print valid checksum else invalid
example: 321543 take 3 saperately and
let sum of squares be 3^2+2^2+1^2+5^2+4^2 == 3(last digit) then print valid checksum otherwise invalid
Given an n-by-n matrix of 0's and 1's where all 1's in each row come before all 0's, find the most efficient way to return the row with the maximum number of 0's.
Compres String
Test cases
Find merge node of two linked list
example:A->B->C->D
Linkedlist2: E->F->A->B->C->D
Reverse sentence: Example:
"Hello life "
to
"life Hello"
Test cases
Write a function to make the largest number from the digits of a given number.
Example.
number: 32441
Output: 44321
function prototype:
C/C++ : int biggestNumber(int number)
Java : int biggestNumber(int number)
Note: Use minimum , constant space.
Given an array of N integers with +ve & -ve numbers. Find the maxproduct of 3 numbers ? & Test Cases
How do you test a WEB SERVICE (C#)..?
Given an array of N integers with +ve & -ve numbers. Find the maxproduct of 3 numbers ? & Test Cases
How do you test a WEB SERVICE (C#)..?
Given an array of N integers with +ve & -ve numbers. Find the maxproduct of 3 numbers ? & Test Cases
Usually first round consists of phone interviews.Try to finish your programming problems asap as the interviewer expects you to solve atleast 3-4
Perform multiplication of two bytes without * operator!!!
Use shift operations
Perform right rotate operation in C
unsigned char rotate(unsigned char c,int m)
Basically rotate m time the bits of char c
Perform right rotate operation in C
unsigned char rotate(unsigned char c,int m)
Basically rotate m time the bits of char c
Usually first round consists of phone interviews.Try to finish your programming problems asap as the interviewer expects you to solve atleast 3-4
Perform multiplication of two bytes without * operator!!!
Use shift operations
Perform right rotate operation in C
unsigned char rotate(unsigned char c,int m)
Basically rotate m time the bits of char c
Usually first round consists of phone interviews.Try to finish your programming problems asap as the interviewer expects you to solve atleast 3-4
Perform multiplication of two bytes without * operator!!!
Use shift operations
Usually first round consists of phone interviews.Try to finish your programming problems asap as the interviewer expects you to solve atleast 3-4
Perform multiplication of two bytes without * operator!!!
Use shift operations
Perform right rotate operation in C
unsigned char rotate(unsigned char c,int m)
Basically rotate m time the bits of char c
Usually first round consists of phone interviews.Try to finish your programming problems asap as the interviewer expects you to solve atleast 3-4
Perform multiplication of two bytes without * operator!!!
Use shift operations
Perform right rotate operation in C
unsigned char rotate(unsigned char c,int m)
Basically rotate m time the bits of char c
Count smaller elements on right side
eg : [4,12,5,6,1,34,3,2]
o/p [3,5,3,3,0,2,1,0]
#include<iostream>
using namespace std;
class A
{
public:
virtual void f() = 0;
};
class B: public A
{
public:
void f()
{
// f(); //segmentation Fault
cout<<"\bB's f() called"<<endl;
f(); //recursive loop
}
};
void A:: f()
{
cout<<"\nA's f() called"<<endl;
}
int main()
{
A *ptr;
B b;
ptr = &b;
b.f();
return 0;
}
Q-> In this problem.. inside the B class f( ), if we call f( ) before "cout<<" statement it gives segmentation fault and after "cout<<" statement it gives recursive loop. Why segmentation fault is coming. Thanks in Advance :)
K-Maximum Subarray problem
print all possible combination of given n parenthesis. Eg: if n=2 then all possible combinations are: (n stands for number of parenthesis pair open-close)
{}{}
{{}}
Find the successor of a node in inorder traversal.
Algorithm to check a linked list is palindrome or not, each node contains a single character.
How to store a binary tree in a file so that we can re construct the same tree with that file
Given two nodes of a tree, find the first common ancestor of these node.
What data structure you will use if you have to implement google map like utility, you will be able to search the city, you will be able to find shortest path between two nodes. And you have to implement one more feature of auto suggestion which means if user type "Na" then you should show all the cities starting with letter Na in a list. And algo should be very efficient because it should update things as soon as user changes the typed character.
each of 100 students in a school has a unique ranking 1-100. I will select 50 students randomly .
Of the 50 randomly selected student i will select a boy, say ranking 40, and wish to know his relative ranking among the 50 students selected. How do you do this efficiently?
Write a recursive function to convert Binary Code of a number into its equivalent Gray's code and the other way round.
Given a set of intervals, find the interval which has the maximum number of intersections.
Given a string "This is an example" --> Output: "This is an example" There should be equal number of spaces between words.
Given a string "This is an example" --> Output: "This is an example" There should be equal number of spaces between words.
There's a major problem in the implementation of the following class. Can you spot it? How can you fix
the problem? You can propose more than one solution, depending on the requirement specifications of
the class.
#include<iostream>
using namespace std;
template <class T>
class Array
{
private:
T *m_pData;
unsigned int m_nSize;
public:
Array(unsigned int nSize) : m_nSize(nSize)
{
if(m_nSize > 0)
m_pData = new T[m_nSize];
}
virtual ~Array()
{
if(m_pData != NULL)
delete [] m_pData;
}
bool Set(unsigned int nPos, const T& Value)
{
if(nPos < m_nSize)
{
m_pData[nPos] = Value;
return true;
}
else
{
return false;
}
}
T Get(unsigned int nPos)
{
if(nPos < m_nSize)
return m_pData[nPos];
else
return T();
}
};given a 4X4 matrix of characters and a dictionary of all the possible english words, write algorithm to find out all the possible words contained in the matrix by connecting the neighboring cells.
How will you implement the auto complete functionality of any intelligent IDE. Discuss your data structure. Handle all the possible contexts. e.g. handle the cases at local, global and class levels
implement find_replace(origString, stringToFind, stringToReplace) method. Handle all the possible scenarios.
given two sorted arrays, find the median of the combined array efficiently.
Difference between == and === in JScript, Write a method to detect mouse hovering over a text box using CSS style sheets
Design a simple Address book Web application, Discuss all aspects of creating the App , starting from UI to Back-end databases
Design a client-server application in the Application layer of TCP/IP
Write all possible test cases to test a DVD player and a smart phone
Count the bits in a Integer, Swap two numbers without using any temp variable, Find the middle element in the linked list
Write a function to fill in values for a 10 X 10 array. The function should fill the array with random ,non-repeated values every time the function is called.
i got this as an interview question. i was given 2 linked lists of unequal lengths,containing a single digited number in each of their nodes. i was asked to build a 3rd linked list which contains the sum of the two linked lists, again in the form of 1 digit in a node. ex: linked list 1 is 4-7-9-6 linked list 2 is 5-7 then the 3rd linked list would be 4-8-5-3 can someone suggest me Java answer.
______________
Need to write a function
Node addLinkList(Node h1, Node h2){ }
Class Node{ int val; Node next }Convert a sorted doubly linked list to a BST while trying to keep BST as balanced as possible
Convert a BST to sorted doubly linked list.
given an array A which has only 0's and 1's in sorted order , find the occurrence of first '1' in A.
example : A [] = 00001111 , returns 5 .
write a function which takes a string S and a pattern string P and an integer i , and returns the i'th occurrence of P in S.
example S = "abcabcefgabc " , P = "abc" , i =3 , ..returns 10
differencee between REST and SOAP
difference between exe and dll
difference between hashtable and hash map
|_|
|_| |_|
|_| |_| |_|
|_| |_| |_| |_|
|_| |_| |_| |_| |_|
Each cup has capacity C and once a cup gets full, it drops half extra amount to left child and half extra amount to right child
for Eg : let' first cups get 2C amount of liquid then extra amount C(2C-C) will be divided equally to left and right child cup of next level
i.e. C/2 to left child and C/2 to right child
Write a function which takes input parameter as amount of liquid poured at top (L) and height of particular cup (h) index of that cup (i) and it should return amount of liquid absorbed in that cup.
Describe the SOA principles / Web Service standards follow when developing web services
Write a method to create new tree with same structure but the values of each node will be sum of their descendents (sub tree). The leaf nodes will become 0. So if the tree is 50 30 10 40 60 55 75 (PreOrder) then new tree should be 270 50 0 0 130 0 0(PreOrder)
What's the difference between a Linked List and an ArrayList and give me an example of when to use which
What are hashmaps and how do they work?
Tell me about memory allocation (stack vs. heap)
What is the difference between Java and C++?
Given a binary tree return the new binary of given depth.
Example:
0 - 3 -- Should return full binary tree from root to height 3
3 - 4 -- Should return full binary tree from height 3 to 4
A king is about to give a party in 24 hours. For the party they have arranged drinks which will be served through 1000 barrels. Out of jealousy , some one near to king has poisoned one of the barrels. The poison is so strong that even a drop can kill a person. But results are not immediate. A person may die from 13 to 20 hrs. Now king has a duty of finding that barrel. He has 24 hours with him. And he has unlimited prisoners on which the drinks can be tested. Find out the maximum prisoners he would need to find out that barrel.
What data structure to use for finding free parking spot in Parking Lot program? Assume there are million of parkings.
Given a stack of glasses like :
v
vv
vvv
vvvv
.
and a person filling water from the top using a jug. Given that the volume of jug is V , and volume of each glass is 'v' . Write code to find :
1. Number of glasses fully filled
2. Number of glasses partially filled (and what different categories they'd fall in based on half-filled/75% filled etc.)
3. Level to which water would reach.
Hint : glasses in center will fill up faster than those away from center.
Print a binary tree in level by level in Zig-Zag manner
Given n points in 2D space find k points nearest to origin
write a function which takes 7 digits (last 7 nos of a 1800 number), and return 2 words formed out of the last 7 digits. i.e. 1800 GotCard (Got and Card are the two words to be returned). There could be multiple possible pairs of words - return any 2
The root node in the tree is equal to sum of its all descendants and the leafs are assigned value 0, so if your tree is something like 10
20 30
40 50
output will be
140
0 90
0 0
Given a queue with functions as enqueue(), dequeue(), and findmax(). You can use these functions any time. The findmax() should return the largest value in the queue at that point. You can use auxiliary space.
Implement the queue with given operations. Find the max value in the queue.
Do a merge of two binary trees and tell what the complexity of the merging is. The trees consist of m and n nodes respect.
Reverse a stack without using extra stack (i.e. doing in place reversal). (hinted about using double recursion).
Delete a given node of a linked list, when you do not have info about the head or any other node.
The prototype of the function is -
void delete (Struct node* x)
where x is any arbit node of a linked list.
Given a graph (consider it to be a mxn grid). The nodes are node of a binary tree with left and right pointers. The start point (A) is at the left upper corner and the end point (B) is at right bottom corner. Each node points to its adjacent nodes in the grid (the right pointer points to the node on the right and the left points to the node just below it). The nodes at the lower and right edges will have child as null (right null for the right side edge and left null for the bottom edge). The end node at B is having both as null.
How many paths are possible which can lead you to B, if you start from A?
Which Data structure is used in window search...??
1. Who is the (which process) the responsible for windows
2. updates ? How these windows 'Run' (winKey+R) commands work ?
3. Why the run commands won't work for user installed applications ? Any way to do so ?
What does a packet contains, when it is send from source to destination ? How does a packet routes to one NW to an other ?
Some questions on LINUX command level,
A. command to find RAM memory space occupied by each process.
B.What does 'top' command do ?
Given some file sharing scenario & asked to give negative test cases as many as possible ?
Ans: Here he himself was not clear about scenario, was mixing up with Wins functionality & his scenario.
You have a 2 liter & 5 liter jugs and a tank of milk. So using these 2 jugs get 4 liter milk in 5 liter jug ?
Ans: 5-3 =2 (take 3 liters frm 5 and put 2 in 3 liter jug); 5 -1 = 4 (again take 5 liter & fill remaining liter in 3 liter )
Logic to print number and number of duplicates of that number in a given array list ?
Ans: It's very easy if you two for loops, anyone can try out & get it in seconds.
(1) Working flow of DNS & DHCP protocol ?
Ans: Yeah it's routine question, explained in my way.
(2) How does DHCP generates a lease with client name, by association with DNS.
Ans: With DHCP option DDNS updates, explained it. He was bit happy here.
Search sub string in a big string.
You have 1000 pairs of nuts and bolts all of different sizes. 2 nuts can not be compared and 2 bolts can not be compared with each other. pairs of Nuts and bolts are removed and mixed with each other. How will you arrange them now with lowest complexity .. (hint -> USe quick Sort).
Given an expression tree how do you evaluate it and also how do you evaluate for n-ary operators
Find if two rectangles overlap in cartesian space
Construct a Cartesian tree from in order traversal
Explain about test frame worked on ?
Write a C/C++ program that connects to a MySQL server and displays the global TIMEZONE.
Write a Java program that connects to a MySQL server and displays the global TIMEZONE.
Can anyone plz write the whole correct program ??Reply asap.I would be grateful.
In the page 90 of Gayle's cracking the coding interview book, there was a method defined which is used to get the bit at particular position. Method goes like this...
boolean getBit(int num, int i) {
return ((num&(1<<i))!=0);
}
Will this works..? if my number is 8 and I want to get the 3rd position, this return a wrong result
Calculate the number of barber's shop in your city.
String Reduction
Given a string consisting of a,b and c's, we can perform the following operation: Take any two adjacent distinct characters and replace it with the third character. For example, if 'a' and 'c' are adjacent, they can replaced with 'b'. What is the smallest string which can result by applying this operation repeatedly?
Input:
The first line contains the number of test cases T. T test cases follow. Each case contains the string you start with.
Output:
Output T lines, one for each test case containing the smallest length of the resultant string after applying the operations optimally.
Constraints:
1 <= T <= 100
The string will have at most 100 characters.
Sample Input:
3
cab
bcab
ccccc
Sample Output:
2
1
5
Explanation:
For the first case, you can either get cab -> cc or cab -> bb, resulting in a string of length 2.
For the second case, one optimal solution is: bcab -> aab -> ac -> b. No more operations can be applied and the resultant string has length 1.
For the third case, no operations can be performed and so the answer is 5.
Given 2n points on a circle.find the number of ways to draw n non intersecting chords.
Find the number of nodes in a singly link list, it can be both cyclic and acyclic
x*y = a + b*lcm(x,y) + c*gcd(x,y)
It's easy: you are to write a program which for given a, b and c finds the number of pairs of positive integers (x, y) satisfying this equation.
Here * stands for multiplication, gcd(x,y) stands for the greatest common divisor of x and y, while lcm(x,y) stands for the least common multiple of x and y.
Input
The first line of the input file contains one integer T -- the number of test cases (no more than 10). Each of the next T lines contains exactly three space-separated integers a, b and c (0 ≤ a, b, c ≤ 106).
Output
For each test case output one line containing the sought number of solutions to the equation. If there is an infinite number of solutions, output -1 instead.
Example
Input:
3
2 1 1
160 0 90
300 7 5
Output:
2
8
4
Explanation:
In the first test case, the only pairs are (2,4) and (4,2).
Have you ever thought, when given an undirected graph in some problem, that it would be easier to solve it if the graph's edges were actually its vertices and the graph's vertices were its edges? This problem is right about this -- unfortunately, not about bears and bees (but if you want, you may think of vertices as of bears and of edges as of bees (or even vice versa)).
Suppose you're given an undirected graph G0 with N vertices and M edges. Let's perform a simple transformation on graph G0 to obtain graph G1 with M vertices so that each vertex of G1 corresponds to a unique edge of G0 and a pair of vertices in G1 is connected by a single edge if and only if the corresponding edges of G0 share a common vertex. Similarly, let's perform a simple transformation on graph G1 to obtain graph G2, and let's perform a simple transformation on graph G2 to obtain graph G3.
All you have to do is to output the number of vertices and edges in G3.
Input
The first line of the input file contains one integer T -- the number of test cases (no more than 10). Each test case is described by a line containing two integers N and M (1 ≤ N, M ≤ 1000) followed by M lines, each containing two integers between 1 and N, inclusive, separated by a single space and describing an edge of graph G0. It's guaranteed that each edge connects two distinct vertices and each pair of vertices is directly connected by at most one edge.
Output
For each test case output just one line containing two integers -- the number of vertices and edges in G3.
Example
Input:
2
3 3
1 2
1 3
2 3
4 4
1 2
1 3
2 3
3 4
Output:
3 3
8 18
Explanation:
In the first test case the given graph is a "triangle". It's easy to see that a simple transformation on a triangle results in the same triangle (as it contains three pairwise connected vertices and three pairwise "connected" edges).
Several days ago Chef decided to register at one of the programming sites. For registering he was asked to choose a nickname and a password. There was no problem with choosing a nickname ("Chef" is his favorite nickname), but choosing a password in a secure way seemed to be a real problem for Chef. Therefore, he decided to write a program which would generate the password of length N consisting of small Latin letters a..z. Then Chef successfully registered at the site and saved the password in a file (as it was too hard to remember).
Today Chef decided to visit the site once again. He entered his nickname, copied the password from the file... "Authentication failed!" was the answer. Trying to understand the reason of this, he noticed that the password in his file had length N+K instead of N! Sure enough of the source of the problem, Chef went straight to his young brother.
And Chef was right, it was his brother who had inserted K random small Latin letters at some random positions (possibly at the beginning or at the end) of the password. Chef's brother didn't remember what exactly changes he had made at all, but he promised that he had done nothing besides inserting letters.
As there is no other way to recover the password, Chef is now starting to remove every possible combination of K letters from the password trying to enter (when Chef obtains the same password as one of the previously entered passwords, he doesn't try to enter using this password again). Now the question is: what is the number of times Chef will receive "Authentication failed!" as the answer before successful entering in the worst case? As the answer might be quite large, output its remainder of division by 1009419529.
Input
The first line of the input file contains one integer T -- the number of test cases (no more than 10). Each test case is described by a line containing two integers N and K (1 ≤ N ≤ 10000, 1 ≤ K ≤ 100) separated by a single space, followed by a line containing a string of length N+K consisting of small Latin letters a..z.
Output
For each test case output just one line containing the required number modulo 1009419529.
Example
Input:
3
2 1
aaa
3 1
abcd
4 2
ababab
Output:
0
3
10
Explanation:
In the first test case, the password is definitely "aa". In the second test case, it can be "abc", "abd", "acd" or "bcd", so in the worst case Chef will guess the correct option from the fourth attempt, thus making 3 unsuccessful attempts
Write a C++ program that connects to a MySQL server and displays the global TIMEZONE.
Do in place sorting of the given array such that all 0's moves to right and all 1's to left and their relative positioning remains same. Input array a =01001011101
output : 00000111111
You are given an unsorted array with both positive and negative elements. You have to find the smallest positive number missing from the array in O(n) time using constant extra space.
Eg:
Input = {2, 3, 7, 6, 8, -1, -10, 15}
Output = 1
Input = { 2, 3, -7, 6, 8, 1, -10, 15 }
Output = 4
You are given n variable length sets with each set like set1: [s1.....e1], set2:[s2.....e2] with the condition that the sets overlap (i.e. if you represent them on number line, they intersect). Now you have to remove the minimum number of sets from here so that the remaining sets are disjoint.
For example you have set S1, S2, S3 with S1 and S3 disjoint and S2 overlapping both S1 and S3 then we remove S2 to get the answer.
Given a binary search tree of n nodes, find two nodes whose sum is equal to a given number k in O(n) time and constant space
I cud think of this algo..Do two inorder traversals, one in the usual (descend to the left
before descendung to the right) direction and the other in the
reversed(descend to the right before descending to the left)
direction.and compare the sum with x..
But i am unable to code it properly..(in C)
Need help
write a program in c# or java or c
print the sequences from the input given by the user separated by semicolon
eg: 4678912356012356
output: 6789;123;56;0123;56;
write a program in c# or java or c that prints saddle points in a N by N Matrix.
saddle point is nothing but a cell values which has greater value among all the cell values in that row as well as it should be the smallest value among the column in which it is found......???
Write a method to reverse a multibyte character string.
Given two strings src and sch, sch is a rotation of src. Write a method to find the rotation point in src. Please provide big-O for time and space.
Why data members are private when we can access them through getter/setters?. Why can't we just make them public.[ How will you convince the interviewer]
Round 4: [HR rounds]
Ans 1: Explaied about InMobi and why should i Join It?
Ans 2. Benefit details.
Q1. As already you have been Offered from ABC , would u accept our offer and why?
Q2. Current CTC ? ABC-Offered CTC ? Expected CTC ?
Round 3 | [With manager]... Discussion regarding Product , Issues etc etc...
Q1. As you know there are a lot of s/w which block adds. How to crack these ADD-Blocker S/w ?
[hints-: Url mapping]
Q2. How will you efficiently Look up Adds for a Particular mobile user. Do it very space and Time bounded manner. Find DS and Design algo for that.
[ Hints -Some concept of Learning technique, Expert System, and Data mining ]
Round 2 | Q2. Explain your Internnship Project. He Asked for the System Model and Mathematical Proof .{ as my project does this } Some Cross Question about the Architecture of the System.
Round 2 | Q1. Design an authentication and Authorization system for a Web-service ? How will you deals with Certificate and Auth-Key Management ?
Round 1| Q3: Find out n-th ugly number ? an ugly number is define as 2^i * 3^j * 5^k.
[Hints -DP]
Round 1 | Question 2: Suppose you are givean an expression E= x1 y1 x2 y2....yn-1 xn.
Where Xi belong to natural number and Yi belongs to { +,*}
you need to parenthesize such that it maximize the value of E ?
Let's change Yi to { +,-,*,/}, then how to maximize E?
Now add % operator in that set..then how to maximize E?
[Hints --Use DP]
Round 1 | Q1. Suppose We want to design a Car-parking system. where car can be parked in FCFS basis, But there are some Spacial person ,say P1,P2,p3..having a priority of x1<x2<x3. can be access car according to their Priority.
Give the Data-structure to implement this. Derive Algo and Find Complexity.
[Hints- Heap +Queue OR Multilevel Feedback Priority Queue OR Multiple Heap Structure ]
How to ensure that starvation will not occurs ? How will you integrate with previous Data Structure ?
[Hints -Ageing Technique OR use Time Stamp ]
Written Test | Q2. A cache contains a list of String of length atmost L.suppose cache contain n String Given a String X (of length g) as input, Find out whether any anagram of X is in cache efficiently? Find out Time Complexity. [Hints - Tries /hash/ bit-map]
Written test | Q1. Find out Inorder traversal of a Binary Tree without Recursion [hints -use Stack]
You are give n images with width length dimensions w1*l1,w2*l2........wn*ln .Now you have write an algorithm to fit these n images on a big rectangle of dimension W*H.
Constraint:
1)Image resolution should not be changed.you can scale the images keeping aspect ratio unchanged
2)You can perform cropping but as minimum as posisble
one unsorted array is given.Find out the index i and j ,j> i for which a[j] - a[i] is maximum.perform in linear time complexity
one unsorted array is given ,find the index i and j and j > i for which a[j] - a[i] is maximum.Perform in linear time
Find k'th element to the last of a linked list.Standard one
You are given C containers, B black balls and an unlimited number of white balls. You want to distribute balls between the containers in a way that every container contains at least one ball and the probability of selecting a white ball is greater or equal to P percent. The selection is done by randomly picking a container followed by randomly picking a ball from it.
Find the minimal required number of white balls to achieve that.
INPUT
The first line contains 1 <= T <= 10 - the number of testcases.
Each of the following T lines contain three integers C B P separated by a single space 1<= C <= 1000; 0 <= B <= 1000; 0 <= P <= 100;
OUTPUT
For each testcase output a line containing an integer - the minimal number of white balls required. (The tests will assure that it's possible with a finite number of balls)
SAMPLE INPUT
3
1 1 60
2 1 60
10 2 50
SAMPLE OUTPUT
2
2
8
EXPLANATION
In the 1st testcase if we put 2 white balls and 1 black ball in the box the probability of selecting a white one is 66.(6)% which is greater than 60%
In the 2nd testcase putting a single white ball in one box and white+black in the other gives us 0.5 * 100% + 0.5 * 50% = 75%
For the 3rd testcase remember that we want at least one ball in each of the boxes.
design Multi level categories in eCommerce website using no sql. How is it better than modified preorder traversal with relational database like mysql.
Given an array, subarray size k and a number ssum, find the number of subarrays of size k that sum up to ssum.
Which of C++, Java languages supports Multiple Inheritance and which does not ? Follow up: What do you think of Java not supporting Multiple Inheritance?
Given two nodes of a BST and all elements in BST are distinct, write code to determine the shortest distance between the two nodes. (unit distance between two adjacent nodes). Nodes dont have parent pointer.
Given references to roots of two binary trees, how do you short circuit determine whether the sequences of the leaf elements of both the trees are same ? The structure of two BTs may be different. Short circuit : for ex. If the very first leaf element of each tree is different, the algorithm should stop immediately returning false instead of checking all the leaf elements of both trees.
they asked some quesyion from fym :
a horse is in chessboard. given its x,y find the probability through program that it will remain in board after n moves.
write algo for longest palindrome?
given two binary trees' root node, judge whether they're mirrored.
how do you perform string compression:
i/p-->str="aabbbcdddd"
o/p-->str="a2b3cd4"
my prog is not working.....(compression of sring)
#include <cstdlib>
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s;
cout<<"Enter String:";
cin>>s;
int count=0;
int i=0,j=-1;
if(s[i]!='\0')
{ if(s[i]!=s[i+1])
{
s[count++]=s[i];
s[count++]=i-j;
j=i;
}
i++;
}
s[count]='\0';
cout<<s;
getchar();
}
given two stacks implemetn queue and give the time complexity
Given k n-length integer arrays which are sorted. Merge them into one sorted integer array . State the time complexity
Imagine that you are developing a text editor. What is the best data structure to implement the buffer of text?
Then imagine that you have to paste 3000chars into your buffer. How does your structure handles that?
Imagine that you have an histogram stored in an array. Now imagine that you can pour water on top of your histogram. Describe an algorithm that computes the amount of water that remains trapped among the columns of the graph. Clearly on the edges the water would fall off. Use the language or the pseudocode you prefer.
Given (i) a non-empty binary search tree with double values (e.g. 3.5) in each node and (ii) a key value K
Write a method to find the closest value to K.
Take an input as integer from user. Check whether it's a palindrome. Say-23432, the answer is true. Check boundary conditions for the input. Consider all cases--+ve/-ve numbers.
Given an n*n matrix. Print the main diagonal elements starting from bottom-left to top-right.
write a program to find min and max element in queue using linked list
write a program to find min and max element in stack using linked list
FInd all nodes which are of distance K from a given node.
A
B | C
| D E ( C children)
| I J | M N (D,E Children
| P ( I children)
| Q ( p children)
for a given node J and distance 2 you should print all the below nodes Q,M,N,C (its children, parent, siblings children) etc....
Implement LRU cache .
An array contains only 0's and 1's. Code the best way to sort it( Time complexity and space complexity). Length of the array could be very large.
First Round " Find the fault in the program...a very big program(:)),with assert on function in Java. He explained Assert will return True/ False(Boolean).......not clear on this one......Hope this helps.......
Write a program to calculate the number of occurances of letters(chars) in a string. Eg:"Test".(This was the second round for Automation Interview in Amazon)Feb 2012
Write a program to Print for n=3,5,7,......
if n=3 print
*
***
*,
For n=5,print,
*
**
****
**
*....so on.....only for odd numbers.
consider a triangle and three persons. Each one is standing on different vertex of the triangle. A forth person standing @ the middle of the triangle will shout as "GO. Then all the three persons will start moving in nay direction but along the edge of the triangle. What is the probability that two person will meet each other?
If I have a name as a string and a phone number associated with each name. (Name is unique).... and operation to be performed is search then which data structure will be the most efficient ?
What is the difference between static and global variable in C?
Design an infinite loop.. which data structure to use
Assume we are playing a online game with friends in Net . Client sends message calles Ping messages to know connectivity to server.
For each message client sends it also sends Map(assume java HashMap) of connected peers for each message . The game server recieves the message ,
takes the HashMap and for each peer checks the connectivity for each peer with the current machine and sends back the connectivitystatus to client .
There are millions of clients connected to game server and every client sends the ping messsage 100 times per sec .
How should you design the ping message such that the memory over head can be reduced and performance can be improved.
I have simple collection of string objects might be around 10 elements ,
but i use this collection in production environment such that the we search for a given string in that collection millions of tiimes ,
what is the best collection or data structure we can use to get the best results so that seach operation can be performed in 0(1) time
we can use HashMap here but the order of search there is in constant time not 0(1) i want to make sure that search is 0(1).
Our data structure must return true if present , else false if not present
Search an element in a 3-D sorted array without modifying the given array.
Given a String - aaaabbbbcc, convert the given string in to a4b4c2 without using extra memory. ( Note that every character appears more than once in input string and the repeated characters are contiguous)
1. Write algorithm for Binary Search and derive its time complexity.
Also, compare the running time T1 of linear search algorithm with running time T2 of binary search algorithm when (i) n=1000 and (ii) n=10000.
can anyone share his campus interview experience with Amazon ?
a doubly linked list, the right pointers are point to the next node, the left pointers are point randomly. How do a deep duplication of this linked list structure.
Write a program to reverse every K elements of a linked list.
Example: K = 3
1->2->3->4->5->6->7->NULL
Output: 3->2->1->6->5->4->7->NULL
Algorithm 1 does a particular task in a "time" of N3, where N is the number of elements processed. Algorithm 2 does the same task in a "time" of 3N + 1,000.
a:- What are the Big-O requirements of each algorithm?
b:- Under what conditions, if any, would the "less efficient" algorithm execute more quickly than the "more efficient" algorithm?
Explain WCF?
What is Webservice?
What is SOAP Protocol?
Difference between HTTP and TCP?
How you will create automation framework?
Reverse a string and write test case?
Get all Duplicates from Array, Optimize and Type of Data Structure.
Sealed AccessSpecifier,Complete Scrum Process
Code Coverage for a Test Case ?
WCF Question, Test a WCF Services etc
If a function has 2 if block( not nested) , how many test case you will need for code coverage?
What is idempaotence webservice?
Given a web service such where the input is the TokenID and it lets the user download the Product. Write test cases to test this webservice. Its a vague q's
If a function has 2 if block( not nested) , how many test case you will need for code coverage?
10) Explain WCF?
11) What is Webservice?
12) What is SOAP Protocol?
13) Difference between HTTP and TCP?
14) How you will create automation framework?
15) Reverse a string and write test case?
16) Get all Duplicates from Array, Optimize and Type of Data Structure.
17) Sealed AccessSpecifier
18) Complete Scrum Process
19) Code Coverage for a Test Case ?
20) WCF Question, Test a WCF Services etc
Given a web service such where the input is the TokenID and it lets the user download the Product. Write test cases to test this webservice. Its a vague q's
If a function has 2 if block( not nested) , how many test case you will need for code coverage?
9) What is idempaotence webservice?
10) Explain WCF?
11) What is Webservice?
12) What is SOAP Protocol?
13) Difference between HTTP and TCP?
14) How you will create automation framework?
15) Reverse a string and write test case?
16) Get all Duplicates from Array, Optimize and Type of Data Structure.
17) Sealed AccessSpecifier
18) Complete Scrum Process
19) Code Coverage for a Test Case ?
20) WCF Question, Test a WCF Services etc
Given a web service such where the input is the TokenID and it lets the user download the Product. Write test cases to test this webservice. Its a vague q's
A number is given asked to find the all combination with permutation from the digit which makes the sum equal to given number for example for number 4
1 1 1 1
1 1 2
1 2 1
2 1 1
2 2
1 3
3 1
if number is 5
then output should be
1 1 1 1 1
2 1 1 1
1 2 1 1
1 1 2 1
1 1 1 2
3 1 1
1 3 1
1 1 3
2 3
3 2
1 4
4 1
1 2 2
2 1 2
2 2 1
Given a set of unique numbers from 1 to 1000, propose a data structure that allows you to perform the following operations in constant time.
1- Insertion,
2- Deletion,
3- Searching,
4- Get any random number.
Write a function to convert an IPv4 Address in string format to an unsigned integer
Given a function
int strcspn(string find, string src)
code the most efficient way to return the index of first character that matches in the find string of any character in the src string.
example:
find="ttbbcca"
src="ggabba"
Given an unsorted array of integers with duplicate numbers, write the most efficient code to print out unique values in the array. Give the big-o for your algorithm. What are the pros and cons (in the context of hardware usage) of your implementation?
two arrays a and b of size n+2 and n, resp. The array b is obtained from a by removing two distinct elements, say x and y, and randomly shuffling the remaining ones.
Given a and b, find the removed elements x and y. Do this in O(n) time and O(1) space.
Given a sorted array of size n+1 having all the elements from the range 1..n with only one duplicate element, find the duplicate element.
e.g. if n is 10
then the array could be.
1 2 3 4 4 5 6 7 8 9 10
where 4 is the duplicate element.
What is the use of interfaces in Java?
Give a professional answer and not a simple one like they are used in place of multiple inheritance or they facilitate OOP in Java, etc..
Also can you do without interfaces?
Give logic for implementing "diff" command in Linux.
Consider various test cases and explain what will happen in each. The two files are source code and are huge..
For e.g.
File 1: 1-2-3-4
File 2: 1-3-4-2
.if a file has million stars coordinates how would you find the nearest 100 stars. Interviewer asked various variations of this questions and their space and time complexities
OOPs design of a file system
find the duplicate number in a an array of elements which had (1-n).After I gave and answer, he asked how would you improve it with out two iterations. (Ans was to calculate the sum to n terms and there by u can find the duplicate) and complexities
What happens when a URL is typed into address bar of the browser.
How do you scale a system to handle large amounts of data.
Design elevator system
Write a program to find the next biggest number in given number ,using the same numbers only.
i.e. input -685 output-856
n numbers (both +ve and -ve) are arranged in a circle. find the maximum sum of consecutive nos. Do this in O(n) time
E.g.: {8,-8,9,-9,10,-11,12}
max = 22 (12 + 8 - 8 + 9 - 9 + 10)
How does a static member function work?
Where are they stored in memory?
Where the no static member functions of a class are stored in memory
What is a process and what is a thread? What are their differences and similarities? Can you have processes in processes? How do you prevent deadlocks?
NB:: The questions weren't this direct!
Write function that takes two integers m and n respectively. The function should flip the nth bit of m, counting from the LSB and return the resulting value.\
By flip, the interviewer meant change 0 to 1 and 1 to 0. For instance, if you were passed in 8 and 3.
Convert 8 to binary and you have 1000, now we flip the 3rd bit and we have 1100, then we convert this back to decimal(which would be 12)and return the answer.
You are given a linked list. Apart from the normal "Next" pointer, there is one more pointer(random ptr) in each node which points to some random node of the list. How will you create a clone of such a list? (In less than O(n^2))
//Error with the following code,can anyone correct the //following code for queue using two stack getting //compilation error in constructor
#include <cstdlib> // system definitions
#include <iostream> // I/O definitions
#include <fstream>
#include<string>
#include<stack>
#include<vector>
using namespace std; // make std:: accessible
using std::stack;
using std::string;
template<typename T>class Myqueue
{
stack<T> s1,s2;
public:
Myqueue(){
s1=new stack<T>();
s2=new stack<T>();
}
int size()
{
return s1.size()+s2.size();
}
void add(T value)
{
s1.push(value);
}
T peek()
{
if(!s2.empty())
return s2.peek();
while(!s1.empty())
s2.push(s1.pop());
return s2.peek();
}
T remove()
{
if(!s2.empty())
return s2.pop();
while(!s1.empty())
s2.push(s1.pop());
return s2.pop();
}
};
int main()
{
Myqueue<string> str;
/*str.Myqueue();*/
string str1;
str.add("devesh");
str.add("pankaj");
str1=str.peek();
return 0;
}
Yesterday, I had an interview. There they asked me when the code optimization happens? Say,
int abc;//Global variable
abc = 3;
if(abc == 3)
{
printf("abc will be always 3");
}
else
{
printf("This will never executed");
}
Now the question is when the optimization happens? A... At Run time B... At compile time. I answered at compile time... To me I thought, compiler checks for volatile keyword at compile time. If the variable is not declared as volatile then it optimizes the code. But, when the compiler comes to know that, this variable is never ever going to be other than 3? If it is at run-time, then when compiler comes to know that variable is never ever going to be other than 3? Because if the variable is going to be changed after this part of the code executed. Please clear my doubt
You have given a huge array...millions of bytes..( aka sparsh array) . there are numbers in the array in the range x to y . how would you sort the array?
A shop sells things (suppose apples) in packages of 6, 9 and 17; it cannot break the packages while selling. Given an input number (required number of apples), write an algo to find if those many number of things (apples) can be given/sold to the customer without breaking the packages.
Given the input number your algorithm should return true or false telling whether we can give the apples or not.
implement "fill with paint" function which fill the screen(2d array) with respect to a given point and color,fill until border of screen or same color is met.
hint:BFS algorithm
Q: Given a collection of records which have fields like first name, last name, describe how would you store them in a hash table. Each object passed is to be stored in the hash table and the key has to be returned for subsequent retrieval.
A: Explained about how hash tables work, hash function, what should be the table size (prime number), organization of the hash tables(whether each location in the table stores set of values or single value), from there moved on to collision, collision resolution techniques like open addressing, linear chaining etc.
Q: How would you print 1000 factorial(1000!). The hint he gave was 70! = 1.19785717 × 10 **100 which does not fit in any data type.
A: Given that we just have to compute the factorial and print the value, loop over from 1000 to 1 and keep on accumulating the product. But pretty soon, the intermediate product wont fit in any data type and data truncation happens.
The trick is to represent the intermediate product as linked lists and then keep multiplying the numbers in a loop from 1000 to 1
Lets say the intermediate product you obtained is 125 and you want to multiply with 3. Represent the product as
5->2->1
And multiply the product with 3.
He agreed to this answer. He did not ask me to code this.
Q:Given an input array of unsorted elements, sort the array using binary search technique.
A: Build a bst out of the unsorted array by looping over the array and inserting each element to the tree.
Once you have the bst do inorder traversal.
Gvien an array of integers return the integers that are greater than the avegare of that array
int[] GeraterthanAverage(int[] a)Our website is making a lot of HTTP with over 40 icons and a couple very large gif images. How would reduce the number of requests.
A student is very fond of linux and likes Linux Words a lot. A Linux Word is a word that consists of only the letters L, I, N, U, and X in that exact relative order. There must be exactly one L, exactly one I, one or more Ns, exactly one U and exactly one X. Case does not matter. For example, "Linux", "Linnnux" are Linux Words, whereas "Llinux", "Linuxx" are not.
You are given a String Word which you must turn into a Linux Word. For each character in word, you can either replace it with a different letter or leave it unchanged. No other operations, like inserting new characters or deleting existing characters, are allowed. Print the minimal number of characters you must replace to get a Linux Word. If it's impossible, return -1.
Input Format
First line will be the number of testcases N, the following N lines will contain N words without any space.
Output Format
N lines printing the desired output.
Example
Input
4
Linux
LinnnnnUx
LNux
Codecrackers
Output
0
0
-1
12
Reverse a string and also check whether it is palindrome or not while you are reversing
you have given 2n+1 numbers in which 2n numbers are repeated means every number is having duplicate value.find that non repeating number in constant space and o(n) time.i told him using XOR.
then he gave me 2n+2 numbers in which 2n numbers are repeating like above now you have 2 different number.find both number in constant space and o(n) time.(f2f 4th round)
you have given 3 task. you can run it using process or using thread. means 3 different process or combining them and run 3 different threads .which will you prefer and why?(f2f 4th round)
you have to convert binary search tree into doubly link list in constant space and link list should be sorted(f2f 3rd round)
you have given 2n+1 numbers in which 2n numbers are repeated means every number is having duplicate value.find that non repeating number in constant space and o(n) time.i told him using XOR.
then he gave me 2n+2 numbers in which 2n numbers are repeating like above now you have 2 different number.find both number in constant space and o(n) time.(f2f 4th round)
you have to convert binary search tree into doubly link list in constant space and link list should be sorted(f2f 3rd round)
Swap 2 variables without using a temporary variable
Round5 | Q2 : Suppose, Amazon have a Logging system Like This:
They Track all logs daily basis, stored in separate log file.Log contains a collection of tuples of Customer ID and Page ID. The length of Customer ID and Page ID is L1 and L2. Suppose We have a log of D-days , and size of each log fine can be Order of n , where n be the number of customer.
In a most generalized situation, you can assume that a customer can visit the same page multiple times in a day or any number of days.
We are interested to find out the number of Distinct customer visited at-least p distinct pages within exactly T days.
Propose a Data Structure to be use to solve this problem efficiently . Design an Algorithm to solve this problem and Find out the complexity of the algorithm.
{Hints:- Double Hashing/ {Hashing +Tries/BST }}
Round5 | Q1 : What is E-commerce? What are the Basic Issues in E-commerce System? How Will you Address these issues ?
Round4 | Q4 : Explain the Run Time Polymorphism in OOPs. Why it is important ?
Round4 | Q3 : Tell me Something about your the previus work in ABC ? Why u want to leave ABC ? And Why Amazon ?
Round4 | Q2 : Design a Architecture of Online Movie Booking System . Find the possible issues and Idea to Resolve them. How do you optimize the Performance against all these issues.
Round4 | Q1 : Expain all Concept of OOPs.
Round3 | Q2 : Given a Cache of k-length Strings of size n,. Given a String X, We can to convert to another String Y using the following two Rules:
R1:you can change only one character at a Time in stepwise Transformation
R2: All intermediate String in the transformation must be also in cache.
Cache has also an API : Called Is_Transformable(X,Y) return Ture if it is possible to transform X to Y, without violating the Above rule.
Assume that Cache is fixed size and there is a sequence of Query of Checking the possibility of Transformation is coming to The API of Cache.
the Question is : What Data-Structure U can use to implement Cache ? It might need some Initial Complexity to Organize the data , for efficient lookup, and provide service to APIs.
How can u implement the API in O(1).
Suppose we add one more API which calculate minimum number of Steps required to transform X to Y, How do u solve this problem in O(1).
[Hints: Graph Algorithms and Transitive closure ]
Round3 | Q1 : Given a Cache of n String Having length of k each, on Alphabet ALPHA where |ALPHA|=t, Find out number of 2k-length string constructable from the cache, where all sub-string of Resultant sub-string are also in cache ? What Data-structure should you use to Lookup cache? Design an Algorithm to find the count Efficiently? Calculate the Time/Space complexity of the technique. [Hints -Tries ]
Round2 | Q3 : What is Heap Tree? How you implemnt a Priority Queue using Heap.
Round2 | Q2 : Given A Binary Tree of size n , Find Out a Matrix M[n][n], where M[i][j]=1 if i is predecessor of j, else M[i][j]=0. [Hints DP]
Round2 | Q1 : Given a matrix pxq, You start from top left and have to reach the bottom right. Can only traverse right or bottom. How many ways are there to reach at the bottom right?. So If I allow all 4 way move is possible what will be the ans ? . What happened if i make some Restricted Move ? [Hints DP , Backtracking ]
Round1 | Q4 : An array contain +ve and -ve element, find the longest contiguous sub array whose sum is 0 : [hints - Hashing]
Round1 | Q3:Write a function to generate all possible n pairs of balanced parentheses.
For example, if n=1
{}
for n=2
{}{}
{{}}
-----
[Hints -DP]
Round1 | Q2: Is it possible to build a heap only from inoder traversal ? Why or Why Not ? Write Code/Algo of the Same. Proof the correctness of your Algorithm. {hints-D&C]
Round1 | Q1: What is Heap Tree? Explain With Example.
Written Test * Q4: Given a function getInorderSuccessor which takes a BST (Binary Search Tree) as it's parameter. Every node has an extra pointer "next" , which is intialized to null, fill next with node pointers which represent Inorder Successor. [Hints -Recursion/Stack/DP]
Written Test Q3: You are given a linked list which has the following structure
Code:
linkedList {
data
*nextLink
*randomLink
}*nextLink will always point to next node in the linked list
*randomLink will point to any random node node it the list (or NULL)
Now given a list L write an algorithm to create replica of the list( say L') in O(n) time and O(n) space. [Hints- Need Double Pass/Hashing]
Written Test Q2: In given array of elements like [a1,a2,a3,..an,b1,b2,b3,..bn,c1,c2,c3,...cn] Write a program to merge them like [a1,b1,c1,a2,b2,c2,...an,bn,cn]. We have to do it in O(1) extra space. [Hints- D&C or swapping]
Written Test Q1: Given a root and a node of a BST tree, write a function which print all the nodes which are a 'k' distance from the given nodes in sorted order. (distance can be upwards and downwards) [Hints -Recursion]
Given numbers 1 to 1000, suggest a data structure to store them such that following operations can be executed in constant time:
1- insertion,
2- deletion,
3- searching,
4- get_any_number (means return any number if present in the data-structure otherwise return -1).
Test a coffee cup? Write the test cases for the handle of a coffee cup? How would you do compatibility test of the handle?
Given a robot and a Maze in a game. Following our few of the primitives:
bool IsMazeExit();
bool Forward();
void RightTurn();
Constraints:
Every room in the maze is a square. Each room has 2 doors. Robot can call IsExitMaze() when in a room and identify the exit. Forward moves the Robot forward few steps and if it finds a wall it returns to its position. Right turn turns the robot right 90 degrees.
Write a method to find the exit
You are given have a datatype, say X in C. Determine the size of the datatype,
without declaring a variable or a pointer variable of that type, and, of course without using
the sizeof operator!
Print continuous alphabets from a sequence of arbitrary alphabets
For example:
Input: abcdefljdflsjflmnopflsjflasjftuvwxyz
Output: abcdef; mnop; tuvwxyz
Input: AbcDefljdflsjflmnopflsjflasjftuvWxYz
Output: abcdef; mnop; tuvwxyz
how to find the sorted median of a continuous stream of integers. let the stream is 0,1,2,3,4 the median is 2. now let -2 comes and the median for stream -2,0,1,2,3,4 still the median is 2 or it can be 1. now again -4 comes the median for the stream -4,-2,0,1,2,3,4 is 1.
Find number of children at every level in n-ary tree.So root must able to identify number of children node at each level
This could be a good interview question.
Input: Given an array of objects of type
Class Matrix {
int[][] mat;
}Output: Find a product of all these matrix object ( their matrices ), or over a maximal set.
Things to ask
a ) How will you use this array of Matrix objects and them a valid order to be able to multiply them ? We you can create a graph. The nodes are these matrix objects. An directional edge goes from one node to another with the size is of form m*n & n*p. After the graph is drawn, find a path which goes thru' all the nodes. If there are multiple paths covering all nodes break at anyone. If none exists find one which covers maximum nodes. Ideas on this ?
After that is done use dynamic programming tecniques to find the order in which these matrices must be multiplied.
Ask the candidate to draw class diagrams. See if can use the some patterns to separate out the algorithms etc ( like ask him to program to an interface which gives the order. One could be using DP other could be directly operating on the order give naively )
random(0,1) is a function that generates integers 0 and 1 randomly ... using this function how woud you design a function that takes two integers a,b as input and generates random integers including a and b...
You are given a function printKDistanceNodes which takes in a root node of a binary tree, a start node and an integer K. Complete the function to print the value of all the nodes (one-per-line) which are a K distance from the given start node in sorted order. Distance can be upwards or downwards.
Get the top 3 frequently used words in a book. The book contents are given as a single text file.
I used hashmap solution. The interviewer said its not optimal. Use a combination of two or three data struct.
We are given a set of n distinct elements and an unlabeled binary tree with n
nodes. In how many ways can we populate the tree with the given set so that it
becomes a binary search tree?
Assume we have n people. Each one has a starting time and ending time. For any people, set flag to true if his/her time range overlaps with anyone else's.
Need O(n) solution or very simple O(nlog(n)) solution.
Imagine you are a contractor who builds houses. Building of every house takes man power. Example: HouseA (manpower to build 20 days, profit when sold = 20K,
HouseB manpower to build = 5 days, profit when sold = 11K,
HouseC manpower to build = 5 days and porfit = 10.5K )
Write a function which takes total available manpower as parameter and returns which house building will give max profit.
So for this example if we pass 15 days to the function the answer would be HouseB and HouseC.
Out put ?
#define SQUARE(x) x*x
main() {
int s;
s = 64/SQUARE(4);
print ("%d", s);
}
A. 4 B. 64 C. 16 D. 128
Ans: Answer is 64 -> 64/4*4
Question on &&, || and ++ operator. Give an expression with combination of these operators and asked to choose evaluated output.
main() {
int *p;
print ("%u %u", *&p, &*p);
}
A. Address Address B. Value Address
C. Address Value D. Compilation Error
Output ?
main() {
int x = 2;
switch(x) {
case 1.5: print ("One");
case 2.5: print ("Two");
default: print ("Zero");
}
}
A. One B. Two C. Zero D. None
You have given two polynomials .. You have to choose a data structure which will be used for addition of both polynomials :-
Condition :-
polynomials are very huge ..(n is very big)
a + bx +cx2 +...... +nxn ..
c + dx +ex2+...... +nxn ..
you have to store the polynomial after sum .
Asked these three questions which are similar but not same.
Q1: Output ?
int main() {
int i=-3, j=2, k=0, m;
m = ++i && ++j || ++k;
printf ("%d %d %d %d", i,j,k,m);
return 0;
}
Q2: Output ?
int main() {
int i=-3, j=2, k=0, m;
m = ++i || ++j && ++k;
printf ("%d %d %d %d", i,j,k,m);
return 0;
}
Q3: Output ?
int main() {
int i=-3, j=2, k=0, m;
m = ++i && ++j && ++k;
printf ("%d %d %d %d", i,j,k,m);
return 0;
}
Write function compress(char* strSource)
it should do the following .
repeating chars in sequence should be replaced with char & count, in case count is 1 no need to add any integer.
Example - AAAABBBCXYZEEEEPPPPPKKABC
should be A4B3CXYZE4P5K2ABC.
you are supposed to iterate the array only once, and modify the same input parameter, do not create any new string.
write a function strRemove(char *source, char *remove )
This function will delete all the chars that exist in string remove from array source, number of iteration should be only 1. Make the searching efficient.
Example
("amazon development center", "aenr")
"mzo dvlpmt ct".
Criteria - First parameter should be modified , no need to create an extra string.
(Answer - Put the second array in a hash table, like array of 256 chars, to search which are the chars needed to be removed with complexity o(1) )
you have two BST , they contain the same amount of elements "N" but there structure is different. how will you cross check that the trees are identical with complexity O(N). Also how will you do the same in case its only Binary tree and not a Binary search tree.
(written test )Write code to traverse a binary tree and save all the elements found in a sorted order in double link list.
You have a table which contains huge data may be crores of records and a cache which can contain only 1000 records. Query is done on the basis of some unique ID. When any query happens data should be copied to the cache, but the records which are used least amount of time should be removed and should be occupied with newly added records from table.
Cache should provide two mechanism , search for record(s) on the basis of a unique id & remove the records which used least amount of time. Cache can contain max 1000 records, and record should be available in cache even after your query is done. So records in cache is refreshed only when new query is done and new record arrives which do not exist in the cache.
A news paper agency wants an application through which customers can select the news paper & magzenes they need on daily basis (ex day1 -> he need paper1 ,paper2, magjene1, day2 -> none , day3 - paper4 ) etc.. how registration and billing will be done, Provide a high & low level diagrams for it. which are the classes needed for the same.
Two chess players want to play chess online with each other using facebook. Which are the classes you need for it and what are the APIs needed for the same. How one user will inform other once he made a move from his side .(Client server architecture .) . How a client will reduce the unwanted number of hits to server 2) once user1 has made a move how user2 will be informed quickly. 3) how the chess board position will be propagated from user1 to user2 with least amount of data . 4) Tell the security measures to make this game efficient (asked what is BUT and how to solve it) .
What is containment and aggregation in COM. What happen to the scope of the object been created in both the case, do they die automatically or you need to delete them.
How will you implement file search facility in windows, so that you will save the search and indexes for future references. Provide the design & tell the classes needed for the same.
You are given a paragraph , which contain n number of words, you are given m threads. What you need to do is , each thread should print one word and give the control to next thread ... this way each thread will keep on printing one word , in case last thread come, it iwill invoke the first thread ... procedure will repeat until all the words are printed in paragraph. Finally all the thread should exit gracefully. What kind of synchronization will use ? Answer only the logic to implement (not complete code)
you have 100 elements from 1 to 100 but my mistake one of those number overlapped another by repeating itself.
Ex. in 1----98,99,100 .... 99 overwrite 2 , so the array becomes ... 1,99,3,4,----99,100 .. Array is not in sorted format , how to find the repeating number ?
Right a program which will perform the following task ->
In a binary tree , if a root is greater then the sum of two child nodes , then the new value of same root will be sum of child nodes , else the right // left child should reinit to such a value, so that the sum of the child nodes will be equal to the value of root node.
(I asked him the answer , he told u need to do manipulation twice, 1) while parsing the nodes 2)while unwinding i.e. again recheck the values.
class Empty {};
Empty e;
What is generated for e? If you look at it in a debugger what will you see?
(This was actually Solomon Page, on behalf of BBG.)
Which of the following cannot be checked in switch - case statement ?
A. Char B. Int C. Float D. enum
Ans: I verified, answer is C (float).
Calculate how many IP addresses are available in IPv6 address.
Explain stic key word while function declaration.
Given Infix expression and asked find postfix exp.
Program to count leaf nodes in binary tree.
Write program to find 2-nd largest element in an array with single loop.
out put
main() {
unsigned int x;
int y;
x=3;
y=-2;
if(x>y)
pf ("x is greater");
else pf("Y is greater");
}
O/P of the program
main() {
int *inptr, temp;
temp=10;
intptr=&temp;
char *chptr;
*chptr=*intptr
print "%d %d", sizeof(inptr), sizeof(chptr);
}
Char ch='Z'; ch is stored as
A. Z
B. ASCII value of Z
C Z with single quotes
D. A&B
Given an array of n elements. The array can have duplicates.
Now sort the array based on frequency of distinct number in array.
eg: a= [3,4,2,5,3,3,4,2,1,5}
output = {3, 4,2,5,1} coz, 3 occurs thrice, 4,2,5 occurs twice, so they are retained in order of there occurrence in original array, and at last 1, as it appears least number of time.
.
Compute the factorial of an integer using minimum number of multiplications. assume no overflows
Find O/P
#define prod(x,y) x+y*x-y
main() {
print ("%d", prod(3,4));
}
There are 22 gloves in a drawer: 5 pairs of red gloves, 4 pairs of yellow, and 2 pairs of green
There are four people who want to cross a bridge; they all begin on the same side. You have 17 minutes to get them all across to the other side. It is night, and they have one flashlight. A maximum of two people can cross the bridge at one time. Any party that crosses, either one or two people, must have the flashlight with them. The flashlight must be walked back and forth; it cannot be thrown, for example. Person 1 takes 1 minute to cross the bridge, person 2 takes 2 minutes, person 3 takes 5 minutes, and person 4 takes 10 minutes. A pair must walk together at the rate of the slower person’s pace. For example, if person 1 and person 4 walk across first, 10 minutes have elapsed when they get to the other side of the bridge. If person 4 returns the flashlight, a total of 20 minutes have passed and you have failed the mission.
how would you design a rate limiter in a client to control the number of transactions it requests the server.
How do you check if an entered text in a textbox is a student email address (ends with edu). special case xyz@alumni.univ.edu should be rejected
Give data structures for the following problems in making an employee management system:
1) given a manager give all the employees he manages ( one to many relationship)
2) represent organizational structure of the company
Write code for the following problem:
find the element in the array that appears consecutively in the array max number of times. Should be O(N)
eg. 1113333244111 ans. 3
How do you check if an entered text in a textbox is a student email address (ends with edu). special case xyz@alumni.univ.edu should be rejected
Give data structures for the following problems in making an employee management system:
1) given a manager give all the employees he manages ( one to many relationship)
2) represent organizational structure of the company
Write code for the following problem:
find the element in the array that appears consecutively in the array max number of times. Should be O(N)
eg. 1113333244111 ans. 3
Write a efficient power function.
int pow(int x, int y) for calculating x^y.
especially for the case when y is of the form 2^n.
int error()
{
char *buf=(char *) malloc(10,sizeof(char));
return buf;
}
whats the error....?
warm up question
In a car odometer, what is the smallest number of miles you can travel to go from one palindromic odometer reading to the next palindromic odometer reading? (e.g. 003300 -> 004400 would be 1100 miles).
Write a program that finds the largest palindromic number that’s the result of multiplying two four-digit numbers (1000 through 9999) without converting the number to a string first (i.e. a pure-numeric palindrome test)
Several Sql Queries.
eg. relation student -> Student Name| Subject 1| Subject 2| Subject 3 | Subject 4 | Subject 5|
Q- Now find all those students whose subjects are DS or Networking.
7)Search for a element in array in log(n).
{ 5,7,8,9,10,1,2,3,4}.
6) Write floor and ceiling function to calculate sqrt(n).
Use any statistical formula to calculate sqrt(n). You dont have to use sqrt function as such.
5) Find second non repeating element in array.
4) Draw a DFA that accept string containing even a's and odd b's.
3) Reverse string by words. Give another algorithm other than reversing whole string and then reverse every word.
2) Inplace Transpose of Matrix.
1) Write a program to change big endian to little endian.
Consider a cloak room. It has 3 compartments, small, medium, large
1 medium = 2 small
1 large = 2 medium = 4 small
Design such a system, ensuring maximum capacity optimization of the compartments. Also, make the required number of moves (in-btw compartments) as minimum as possible.
Write class, functions. Wht functions will u expose. What token will you return back to the user.
Given pre order traversal of a tree. It has only 2 type of nodes, N & L (non-leaf, leaf).. Also, every node either has zero or two children.
Produce the tree.
Eg: Pre-order NNLLL
Tree;
N
/ \
N L
/ \
L L
You have the post order traversal of a tree. produce the tree.
Possible?
If not, what other info you need?
Ok you have that info, now produce the tree.
Write code
Generate all the possible substrings using the characters of a given string. Write code. (The order of chars do not matter, i.e., ac <=> ca)
i/p: abc
o/p: { a,b,c,ab,ac,bc,abc}
<Modified the language of the question, to avoid any confusions>
Write a function that returns true if the bit stream has an alternating pattern. For example 000000101010 would return true and 0000001010000 would return false. Also I had to write test cases for the function.
First greater number in an array. Given a large array of positive
integers, for an arbitrary integer A, we want to know the first integer in
the array which is greater than or equal A . O(logn) solution required
ex [2, 10,5,6,80]
input : 6 output : 10
input :20 output : 80
Given two numbers represented by two linked lists, write a function that returns sum list. The sum list is list representation of addition of two input numbers.
eg:
1->2->3 + 4->5->6 = 5->7->9
6->7->3 + 2->5 = 6->9->8
Given a set of strings (large set), and an input string, you need to find all the anagrams of the input string efficiently. What data structure will u use. And using tht, how will u find the anagrams.
Given an array of 0's and 1's, and a number k, find the minimum window that contains k 0's. Write code.
Extension, now the array contains integers from 0 .. 9 ... and another input array of size 10 is given, that contains the number of occurances of a digit. Find the min window that contains the given no of occurance for each digit.
COnsider the column names given in microsoft excel. A .. Z, AA ... Az, BA .... BZ, .......... ZZ, AAA, ..... and so on.
Given a column name (string of charectors), find the corresponding number.
Given a matrix, whose rows and columns (n * n) are sorted. Given a number x, find whether it exists in the matrix. (I told him the O(n) algo, but he wanted a log n solution)
Given an integer, and a number k, do a cyclic shift (left / right) by k bits of the number.
Write an optimal code that returns the product of 3 numbers from an array that is maximum.
Given a Singly Linked lists, write the function that takes as arguments the head of list and a number and then deletes all the nodes with that number.
Given a binary search tree, first find the least common ancestor of two numbers and then generalize it for m numbers.
Given an array in which numbers are arranged first in increasing order and than in decreasing order. Describe an optimal way to find the largest number.
Given a dynamic stream of integral numbers, write a function that returns its median. The numbers may arrive in bursts at any time.
Write a program to find out if the binary tree is balance or not. The tree is balance if the difference between the
left node and right node is equal or less than 1. The above considition is applicable for subtree too..
If tree do not have any child, its height will be zero.
What is the order of above program
Write a program to find out the height of the tree. Tree can have two node (one is left and right node).
If tree do not have any child, its height will be zero.
What is the order of above program
Find the density of the given binary tree
Given two numbers m and n, write a method to return the first number r that is
divisible by both (e.g., the least common multiple)
Write a function to create an mirror image of binary tree
1) Write a iterative program to calculate factorial of N.
2) what is the order of above program
3) Write a recursive program to calculate factorial of N.
4) what is the order of above program
There are two integer arrays ,each in very large files (size of each is larger than RAM). How would you find the common elements in the arrays in linear time.
For an array of integers, find if there are 3 numbers that add up to zero. An algorithm of complexity O(n^2) was required.
Given a random number generator say r(5) generates number between 1-5 uniformly at random , use it to in r(7) which should generate a random number between 1-7 uniformly at random.
Given a big list of "n" integers stored in the disk compute the Top "k" , assume k << n and sizeof(n) > sizeof RAM .
if(fork())
printf("MAGIC\n");
what is output??
int rows=20000;
int col=30000;
void func1()
{
for(i=0;i<rows;i++) {
for(j=0;j<col;j++)
print(a[i][j]);
}
}
void func2()
{
for(j=0;j<columns;j++) {
for(i=0;i<rows;i++)
print(a[i][j]);
}
}which function is more efficient ?
When you type "amazon.com", what happens? explain everything including how the request to site is generated via TCP/IP etc. Also, what is the typically refresh interval for a DNS Cache ?
Write all the possible numbers which multiply to given number. Eg : 12 can be written as 12*1, 2*6,3*4,2*2*4. Dont include 6*2 again or 4*3 as its duplication of 2*6 and 3*4 resp.
Write a function to generate fibonacci number, The function takes two argument. The first one is the starting point of fibonacci series and second one is length. (e.g fib(3,4) will print 2 3 5 8). What are the test cases. Mention your top 5 test case. Mention your top 1 test case
You have a matrix that can have two values black or white. When adjacent cells in the matrix are black they make up a connected component. Write a function that prints out how many component are there in the matrix. Extension: say the matrix is vary large. How can you use multiple core of the processor to solve this problem.
There are two processes. One process(process 1) has a pointer to a variable in the other process(process 2). Now, can the variable be updated using this pointer in process 1?
Given a uniprocessor system, is there any advantage of using threads when the process itself is pretty responsive?
You have a string representation of a number. Convert it to integer value.
Write a function to detect anagram (eg. dad). Extension: Extend it for detecting multiple anagram(e.g dadana has 2 anagram.) What are the test cases. For test cases think about anagram embedded inside anagram (alala).
Determine whether a number is colorful or not. 263 is a colorful number because (2,6,3,2x6,6x3,2x3x6) are all different whereas 236 is not because (2,3,6,2x3,3x6,2x3x6) have 6 twice. So take all consecutive subsets of digits, take their product and ensure all the products are different
Given a 2 dimensional point of a rectangle and its area, find permutations of all the other 3 points of the rectangle in 2-D space.
Ex:- Given X=(0,0) and A=1
(0,1),(1,0),(1,1)
(0,-1),(-1,0),(-1,-1)
....
Suppose you are given an ordered array of strings representing a file system. Ex: {'\', '\Documents\', '\Documents\School\', '\Documents\School\Project.docx', '\Documents\Work\', '\Pictures\', '\Pictures\me.jpg'}.
Write a function that will take this array as input and build a tree.
From the example above, the tree would have a head with the value '\', which has the children 'Documents' and 'Pictures. 'Documents' has children with values 'School' and 'Work', and so on.
given a byte array.which consists of 1 byte char and 2 byte characters, 1 byte character can store value between 0-127,1st byte of 2 byte character can store value between 128-255 and 2nd byte of 2 byte character can store value between 0-255; given a position k find whether it is start of 1 byte character or 1st byte of 2 byte character or 2nd byte of 2byte character
p,p+2 are prime numbers .prove that (p+7) is divisible by 6 .given p>10.
stock market simulation: given a set of values {{v1,t1},{v2,t2}........}vi->value of stock at time ti;suggest a method to determine a single selltime,buytime.to get maximum profit .
How do you partition an array into 2 parts such that the two parts have equal average? Each partition may contain elements that are non-contiguous in the array..
How do you partition an array into 2 parts such that the two parts have equal average? Each partition may contain elements that are non-contiguous in the array..
The columns that I get in a table after a clustering process is not specific but varies from 150 to 210. I need to get the column name that has the max value for each row and add that column name to a target column..
Schema looks like this
cluster_name ---> varchar(20)
col1 ----> decimal
col2 ----> decimal
...
coln ----> decimal
The result of the query should look like this
cluster_name -----> varchar(20)
col_name(that had the max value for that row)------> varchar(20)
col_max(max value across all columns for that row)-------->decimal
should use only mysql query..
Given a sequence of integers corresponding to a stock price over a period of time, write a function that will find the best day to buy and the best day to sell that will yield the most profit.
Given a time of day, write a function that returns the angle between the hour hand and the minute hand. For simplicity, you can create your own basic Time object to be used as a parameter for your function.
Lets say you have a room with 100 doors in it. Initially, all of these doors are open. You have 100 people that will be entering the room. The 1st person toggles every door, 2nd person toggles every other door, 3rd toggles every 3rd door, ... , nth person toggles every nth door. How would you determine the state of all 100 doors after all 100 people have entered the room?
Assume you already have a function that returns a random integer between 0 and integer max (2^32). Create a random number generator that will return an integer between a user-specified range R1 and R2. You can assume that R1 < R2.
"DESCRIBE" and write code to return LCA of any two given nodes in __Binary Tree__.
There is an sorted array rotated unknown number of times. Find the minimum - follow up, return second min and/or second max.
Print the binary tree level by level. Suggest methods. If one of your method is using queue and some delimiter is detect the change in levels, what is its space and time complexity. Prove your analysis. (yes, CLRS style proof is expected)
Given number n, return true if n is prime otherwise false.
Given set of elements and all the elements repeat even number of times and one repeats odd number of time, which is that odd number?
Write class for binary expression tree.
What is polymorphism, inheritance, method overriding.
Check if two linked merge.
Print odd powers of three.
Delete a node in Linked list.
Given 2 arrays which are sorted in non-decreasing order and your told that one of the two arrays have sufficient memory allocated to have elements combined from both arrays, merge the arrays and keep the sorting order.
How do you improve IE?
Test address bar in IE.
Given a sentence, count the palindromes inside the sentence. Do not worry about the palindrome inside a palindrome. Write test cases.
Given two integer arrays which may contain duplicates, report the intersection of both the arrays.
find the largest word made of other words in a list of words...
find the largest word made of other words in a list of words...
Any resources for future bazaar's interview procedure for software devs freshers? What's the company's position in ecommerce
An unsorted array contains elemets 1-1000, we are replacing one element in the array with n , and n is greater than 1000. How can we find out what element got replaced with n
Given an unsorted array of integers, find a 3-element subset that sums to zero
Given a set of points (x,y) in a 2-d plane, which are guesses of a particular unknown point (x',y'), how do find the best estimate of (x',y') using the set of points given.
find common ancestor of 2 nodes in
1. binary tree
2. binary search tree
No parent pointer is given.
given a million integers find the largest k elements
Given an array of ints (positive and negative) and a sum, find 2 numbers in the array whose sum equal to input sum.
Given m sorted arrays each of size n, merge the arrays into one big array.
implement function:
char * get_ip_address(int ip_address)
basically convert input ip_address to user-friendly format a.b.c.d
Check if tree 1 is sub tree of another tree 2
Given 2 sorted arrays, find the kth element in the merged array.
Given 10 billion integers in a disk, find the integer not present. You have < 10 MB of memory.
max sum sub-array problem. Given an array of positive and negative integers, find the maximum sum possible from the different sub-arrays.
You are given the data for the tennis players - the number of games played, wins/losses, years played, etc. Design an algorithm to rank the players. This is an open ended question.
design a locking mechanism.
test 1:
printf("test %s\n", NULL);
printf("test %s\n", NULL);
prints:
test (null)
test (null)
test 2:
printf("%s\n", NULL);
printf("%s\n", NULL);
prints
Segmentation fault (core dumped)
what is the difference in the above tests ? Why is segmentation fault not thrown in test 1 above ?
Check if a tree is a BST.
Find the in-order successor of an element in a BST.
what happens when BSS is mapped to address 0 ?
what does a structure element a[0] mean ? what is it used for ?
what does #define a ## b mean ?
what is the size of short, int, pointer in 32 bit and 64 architectures ?
Design the autocomplete feature (ex:Google Suggest)
Given a file, return the list of all the words which occurs exactly n times in the file
Design and Implement Boggle game for n x n
You have a binary tree. Given two number in that tree, how will you find the least common ancestor ? What will the complexity of this search ?
Suppose you are a search engine owner and want to show adv to make money. How will you filter the advertisements to be shown when users searches for something. Take into consideration that advertisers will not be interested in showing adds to all geographical locations and some types of add may be banned in some locations.
For eg : There is a alcohol selling company. Now alcohol adv is banned in india so this advertisement should not be shown. Also an adv in India might not want to show add in Europe. But Advertisement for Alcohol consulting or addiction etc can be shown. So if someone types alcohol rehab then what strings you will search ? how ill you define which all strings to be searched for ? and what data structure will you use to search ? and what is the algorithm for it ?
Define the algorithm and data structures you will use.
Flatten a binary tree in the its inorder traversal form. Example if there is a tree like
01
0203
04050607
Flatten it to 04->02->05->01->06->03->07
Right of 4 should be pointing to 02 and so on.
The order is inorder traversal order
I was asked to use Recursion
PLease can some one post C# code for this.
GIven a binary tree, print the tree according to the level.
eg
01
0203
04050607
0809101112131415
proceed further to find the mirror image of alternate level
01
0203
07060504
0809101112131415
You have a circular track containing fuel pits at irregular intervals. The total amount of fuel available from all the pits together is just sufficient to travel round the track and finish where you started. Given the the circuit perimeter, list of each fuel pit location and the amount of fuel they contain, find the optimal start point on the track such that you never run out of fuel and complete circuit.
Suppose an array is of the form [i1,i2,i3,i4,c1,c2,c3,c4] where i[1..n] are integer elements and c[1..n] are character elements. Write an in place algorithm so that the resulting array is of the form [i1,c1,i2,c2,i3,c3,i4,c4]. State optimised time and space complexities.
Example: array: [1,7,9,4,a,x,r,d] should become [1,a,7,x,9,r,4,d].
Cache language. If A+B is written as +AB in cache language, solve the foll sums...Very basic
Maths and logic sections very common problems like if one person leaves at this time and other at this time, what time will they meet. BRING A CALCULATOR to solve these. Just simple calci.
There is a game they termed as Mingo. A random generator (like a speaker standing in a group housie game calls out a number) generates out any number from 1 to 1000.
There is a 10X10 matrix. A random generator assigns values to each block of this matrix(within 1 to 1000 obviously).
Whenever, a row or a column or a diagonal is fully filled in this 10x10 from the numbers called out by the speaker, its called a 'Mingo'.
Write a program that will find first Mingo, then second Mingo, then thirds Mingo...and so forth.
write a program to implement the game of tic tac toe.
Given a list, L, of size k. L contains elements between 1 and n. Also given a function RND() such that this function returns a number between 1 and INT_MAX.
Now generate number between 1 and n, using RND(), such that the element should not be there in the list L. All elements should have a uniform probability.
Given a string "abcd" print combinations of length n. Example if n= 3 print abc, abd, acd, bcd. Was asked to use recursion. Can someone please help me with a C# recursive function for this.
compare two strings arrays and return intersection elements in a string array without using 2 for loops?
Design pack of cards
compare two strings and store intersection elements in a string array without using 2 for loops?
Given an array (length n), we need to find the subarray (length k) such that the sum of the first j elements of the subarray equals the sum of the remaining (k-j) elements of the subarray.
For e.g.
Array: 2,2,13,4,7,3,8,12,9,1,5
Output: 4,7,3,8,12,9,1 [4+7+3+8=12+9+1]
Could this be done with a complexity better than O(n^3)
What is the complexity of an algorithm to check whether a binary tree is symetric or not. No need to check the data only the structure needs to be verified.
Design an online movie booking system
Find the nth non-repeating number given a streams of characters in the range of A-Z
Given the number, find the immediate next (larger) palindrome
find square root of a number upto given precision value
String represented as as singly Linked list with one letter on each Node. Need to check whether it is a paliandrome or not. Can use only one String variable other than the Linkedlist
Puzzle:
given a 10x10x10 sized room and a 15 feet large stack of penny. Can you fit all the pennis in this room. Diameter of a Penny is half inch.
Find the top 100 largest numbers from a very large file containing numbers. The file cannot be loaded into the memory.
write algorithm to add two Roman Numeral.
Can you do it without converting Roman Numeral to integer numbers.
print the 5th node from the end of a link list.
Sort Array of String based on char array sort order.
example:
char[] c = {'T', 'M', 'A'}
String[] strArray = {"Adam","Martha","Terry"}
Output : "Terry", "Martha", "Adam"
Write jQuery code to alert a message box when you click on a paragraph with the content of paragraph.
* Why Microsoft?
* What is Cloud Computing?
* How would you design a software application? Discussion about software and hardware requirements. How would you handle increase in load? How would you manage the increase in load without additional hardware?
Write efficient code for Singleton class. I wrote the double-checked locking version. Then he asked for other approaches specifically to reduce the number of lines of code :-/
You have 2 character arrays. The arrays have characters ranging from a-z (all small letters).
1. Merge the two arrays
2. Sort the array
Perform the above in O(N)
Convert the matrix into a linked list (singly or doubly). Nodes have two pointers - right and down.
a1-a2-a3-a4
| | | |
b1-b2-b3-b4
| | | |
c1-c2-c3-c4Find first two numbers whose sum equals a given number in infinite length (stream of numbers) singly linked list.
Write HTML/CSS code to put odd images on left and even number images on right with some text content (basically float images).
(Don't remember the exact wordings) You have 25 red balls, 47 green balls and 3 blue balls in a basket. What is the minimum number of balls you have to pick to make sure you have at least 2 balls of different colors?
Do you know about design patters? What is Singleton?
Operating Systems (in windows):
* Difference between Process and Thread
* Deadlock
* Race condition
Given the following code snippet:
void InsertNode(tNode** node, int i){
if(*node == NULL){
*node = new tNode;
(*node)->pLeft = NULL;
(*node)->data = i;
(*node)->pRight = NULL;
SetRootNode(node);
return;
}
else{
if(i < (*node)->data)
InsertNode(&((*node)->pLeft), i);
if(i > (*node)->data)
InsertNode(&((*node)->pRight), i);
return;
}
}
void Func(tNode **node){
if(*node!=NULL){
Func(&(*node)->pLeft);
tNode *temp;
temp = (*node)->pLeft;
(*node)->pLeft= (*node)->pRight;
(*node)->pRight = temp;
Func(&(*node)->pRight);
}
}
void traverse(tNode** nd){
if(*nd!=NULL){
traverse(&((*nd)->pLeft));
traverse(&((*nd)->pRight));
std::cout<<(*nd)->data<<std::endl;
}
}Let the input given be
98,15,100,10,78,120,5,12,96,110
What would be the output of the following code snippet?
int main(void)
{
tree *bT = new tree;
int i = 10;
int data;
while(i--){
std::cout<<"Enter the node"<<std::endl;
std::cin>>data;
bT->InsertNode(bT->GetRootNode(), data);
}
bT->InsertNode(bT->GetRootNode(), 97);
bT->Func(bT->GetRootNode());
bT->InsertNode(bT->GetRootNode(), 99);
bT->traverse(bT->GetRootNode());
}Options
-98,15,78,96,97,99,10,12,5,100,120,110
-110,120,100,5,12,10,99,97,96,78,15,98
-100,110,120,98,5,10,12,15,78,96,97,99
-None of these
Given the following code snippet:
void InsertNode(tNode**
node, int i){
if(*node == NULL){
*node = new tNode;
(*node)->pLeft =
NULL;
(*node)->data = i;
(*node)->pRight =
NULL;
SetRootNode(node);
return;
}
else{
if(i < (*node)-
>data)
InsertNode(&((*n
ode)->pLeft), i);
if(i > (*node)-
>data)
InsertNode(&((*n
ode)->pRight), i);
return;
}
}
void Func(tNode **node){
if(*node!=NULL){
Func(&(*node)-
>pLeft);
tNode *temp;
temp = (*node)-
>pLeft;
(*node)->pLeft=
(*node)->pRight;
(*node)->pRight =
temp;
Func(&(*node)-
>pRight);
}
}
void traverse(tNode** nd){
if(*nd!=NULL){
traverse(&((*nd)-
>pLeft));
traverse(&((*nd)-
>pRight));
std::cout<<(*nd)-
>data<<std::endl;
}
}Let the input given be
98,15,100,10,78,120,5,12,96,110
What would be the output of the
following code snippet?
int main(void)
{
tree *bT = new tree;
int i = 10;
int data;
while(i--){
std::cout<<"Enter
the node"<<std::endl;
std::cin>>data;
bT->InsertNode(bT-
>GetRootNode(), data);
}
bT->Func(bT-
>GetRootNode());
bT->InsertNode(bT-
>GetRootNode(), 99);
bT->traverse(bT-
>GetRootNode());
}Options
-100,110,120,98,5,10,12,15,78
,96,99
-99,96,78,15,12,10,5,98,120,1
10,100
-110,120,100,5,12,10,99,96,78
,15,98
-98,15,78,96,99,10,12,5,100,1
20,110
Given the following code snippet:
void InsertNode(tNode** node, int i){
if(*node == NULL){
*node = new tNode;
(*node)->pLeft = NULL;
(*node)->data = i;
(*node)->pRight = NULL;
SetRootNode(node);
return;
}
else{
if(i < (*node)->data)
InsertNode(&((*node)->pLeft), i);
if(i > (*node)->data)
InsertNode(&((*node)->pRight), i);
return;
}
}
void Func(tNode **node){
if(*node!=NULL){
Func(&(*node)->pLeft);
tNode *temp;
temp = (*node)->pLeft;
(*node)->pLeft= (*node)->pRight;
(*node)->pRight = temp;
Func(&(*node)->pRight);
}
}
void traverse(tNode** nd){
if(*nd!=NULL){
traverse(&((*nd)->pLeft));
traverse(&((*nd)->pRight));
std::cout<<(*nd)->data<<std::endl;
}
}Let the input given be
98,15,100,10,78,120,5,12,96,110
What would be the output of the following code snippet?
int main(void)
{
tree *bT = new tree;
int i = 10;
int data;
while(i--){
std::cout<<"Enter the node"<<std::endl;
std::cin>>data;
bT->InsertNode(bT->GetRootNode(), data);
}
bT->InsertNode(bT->GetRootNode(), 99);
bT->traverse(bT->GetRootNode());
}options
-110,5,12,96,78,15,99,110,120,
100,98
-5,10,12,15,78,96,98,99,100,11
0,120
-120,110,100,99,98,96,78,15,1
2,10,5
-98,100,120,110,99,15,78,96,1
2,5,110
From the following options, select a statement that is NOT true about immutable objects.
You can use immutable objects in multi-threaded programs
You can use a pointer to create a reference copy of an immutable object, instead of creating a copy of the object
Immutable objects cannot be modified after they are created
An object has to be completely mutable or immutable but partial immutability is not very useful in programs
From the following options, select the correct function that is referentially transparent.
- log(x)
- now()
- strcat(str1,gets())
- rand(0,1)
What features must a programming language and its runtime environment provide in order to support automatic memory management?
1. Dynamic memory allocation
2. Explicit deallocation of data
3. Garbage collection
- 1 and 3, but not 2
- 1
- 3
- 2
A program uses a queue to visit each of the nodes of a binary tree, starting at its root. After a node is processed its children are added to the the end of the queue. In what order do nodes get processed?
Postorder
Breadth-first
Inorder
Preorder
Suppose you have the following code:
void InsertNode(tNode** node, int i){
if(*node == NULL){
*node = new tNode;
(*node)->pLeft = NULL;
(*node)->data = i;
(*node)->pRight = NULL;
SetRootNode(node);
return;
} else {
if(i < (*node)->data)
InsertNode(&((*node)->pLeft), i);
if(i > (*node)->data)
InsertNode(&((*node)->pRight), i);
return;
}
}
void Func(tNode **node){
if(*node!=NULL){
Func(&(*node)->pLeft);
tNode *temp;
temp = (*node)->pLeft;
(*node)->pLeft= (*node)->pRight;
(*node)->pRight = temp;
Func(&(*node)->pRight);
}
}
void traverse(tNode** nd){
if(*nd!=NULL){
traverse(&((*nd)->pLeft));
traverse(&((*nd)->pRight));
std::cout<<(*nd)->data<<std::endl;
}
}
Let the input given be
98,15,100,10,78,120,5,12,96,110
What would be the output of the following code snippet?
int main(void) {
tree *bT = new tree;
int i = 10;
int data;
while(i--){
std::cout<<"Enter the node"<<std::endl;
std::cin>>data;
bT->InsertNode(bT->GetRootNode(), data);
}
bT->Func(bT->GetRootNode());
bT->InsertNode(bT->GetRootNode(), 99);
bT->Func(bT->GetRootNode());
bT->traverse(bT->GetRootNode());
}
Options
-5,10,12,15,78,96,98,99,100,1
10,120
-5,12,10,99,96,78,15,110,120,
100,98
-5,10,12,15,78,96,99,98,100,1
10,120
-98,100,120,110,15,78,96,99,1
0,12,5
Implement Iterator for a n-ary Tree structure.
A large integer is stored in an Array , with each index position storing a single digit of the Number. WAC to increment the integer , stored in the array by one.
Find the character that has maximum frequency in an array of characters. If n is small and dealing with unicode char-space, extra space for hashtable is overhead, can you avoid?
Gave a puzzle - placed two robots and a sensor on the line, write code that will be executed on both machines and make them meet.
Can you mention any issues that you debugged earlier and thought was tough?
Given a binary tree
struct Node {
Node* leftChild;
Node* rightChild;
Node* nextRight;
}
Populate the nextRight pointers in each node.
A kidnapper wants to write a ransom note. He'll do so by cutting character/words from a magazine. Given a note and the magazine (both in form of strings), find out if the note can be formed from the magazine.
Print all the paths from the root to the leaf in a tree
Given a sorted array, construct a balanced BST.
What happens after www.amazon.com is typed by customer?
I showed the feature 'Customers who bought also bought' on amazon.com, and asked to design and implement.
Q. What if memory is not sufficient?
Q. How do DB tables look like?
Q. Can you state what all components are present in the system and how does the control flow after webserver receives the request?
Q. If you use multiple DB calls for every request, it may be very inefficient as you might be serving millions of requests. can you improve?
Given a binary tree where each node contains an integer value and a value k, print all paths which sum upto this value k
what do threads share amongst themselves and what they dont share?Please help me in the ans.I know Heap is shared b/w threads and stack is not shared.What els do the have them in common?
Given a list of words, L, that are all the same length, and a string, S, find the starting position of the substring of S that is a concatenation of each word in L exactly once and without any intervening characters. This substring will occur exactly once in S..
.
Example:.
L: "fooo", "barr", "wing", "ding", "wing".
S: "lingmindraboofooowingdingbarrwingmonkeypoundcake".
fooowingdingbarrwing.
How will you prioritize below 4 projects
1. Minor defects, less business impact but cutomere has reporetd this issue
2 & 3- Projects whose details are not there but its the VP projects
4. Critical project with huge impact on business
( I told 4 first and 2&3 i told since do not have much details so I will work on the first one since bug reported by customer) However correct answer should be (1,4,2&3 since amazon is customer drive company) make sure you do not flunk in this question
Write the test cases for the scenario where you need to verify sum between 1 to 100 inclusive( again you need to tell negative and positive test cases)
What all type of testing will you perform on the google search engin and the Negative and positive test cases( Interviewer was more intersted knowing the types like functional, non functional, performance, load , stress and do not forget to mentioned localization terms in your test case) I told almost 10 test cases and covered most of all type of testing
Give the name of the filed you enter while creating a defect( You need to tell all the filed you have used while creating a defect)
Exit and Entry criteria for the test plan
have you created test plan? What it includes.
Q. Given a singly link list. Tell if the word in the LL is a palindrome or not.
Design Online movie ticket system. How can you make this website faster. What would would you cache?
Q. How will you implement the locker management system? Insertion and retrieval?
Q. Given 3 kind of lockers of size S,M,L. How will you store the data?
Q. A kidnapper wants to write a ransom note. He'll do so by cutting character/words from a magazine. Given a note and the magazine (both in form of strings), find out if the note can be formed from the magazine.
Q. Given a binary tree
struct Node {
Node* leftChild;
Node* rightChild;
Node* nextRight;
}
Populate the nextRight pointers in each node.
Q. Semaphores/Mutex/deadlocks
Q. Can you mention any issues that you debugged earlier and thought was tough?
Q. Polymorphism? object memory layout?
Q. Can you explain how the system works internally when user types www.amazon.com?
Q. Gave a puzzle - placed two robots and a sensor on the line, write code that will be executed on both machines and make them meet.
Q. Find the character that has maximum frequency in an array of characters.
Q. If n is small and dealing with unicode char-space, extra space for hashtable is overhead, can you avoid?
Q. O(n) is also long time if I am processing hugh amount of data, assume several TB. Can you improve the run time performance?
Q. Lets assume you have much more data to process and you have a server farm to process this. Data could be streaming as well.
Q. How will you implement the locker management system? Insertion and retrieval?
Q. Given 3 kind of lockers of size S,M,L. How will you store the data?
you are given with N points on a graph and a point A and range R suggest an algo for finding the points that lies within distance R from A
Design the ArrayList data structure by using Objecte[] & implement add(), delete() and update(int index) method for ArrayList.
Note: Don't use any standard API for extends.
Design aspect :
- How you are making the default size array in grow-able form & how you design delete or update method which can update and shuffle the elements in array[].
Given a string, evaluate the aithmetic expression that it represents . Example return 1 int for string 1+2-10/5
I want to design log in service for banking site.
Design consideration :
1. If User try 5 times wrong password than he should block for 1hr
2. User can try log in from different browser too
3. User can log in again with correct password after 1 hr if he lock on last attempt.
Solution consideration :
1. How to design the data structure for maintaining the user sign in
2. How to design thread or any service which can remove the user from data structure after 1 hr
From the following options, select the OOP mechanism, that allows treatment of the derived class members just like the members of their parent class.
Abstraction
Polymorphism
Decoupling
Encapsulation
You have two relation variables: RelV1 and RelV2. They are NOT necessarily distinct. You
have a set K as a key for RelV1. Consider that FK is a subset of the heading of RelV2 that
involves exactly the same attributes as K.
From the following options, select the option that correctly depicts a scenario where FK can be
considered as a foreign key.
-Every tuple in RelV1 has a K value that is equal to the FK value in some tuple in RelV2
-Every tuple in RelV1 has a FK value that is equal to the K value in some tuple in RelV2
-Every tuple in RelV2 has a K value that is equal to the FK value in some tuple in RelV1
-Every tuple in RelV2 has a FK value that is equal to the K value in some tuple in RelV1
Select the option that correctly describes the database replication concept where two or more
replicas synchronize each other through a transaction identifier.
-Quorum
-Multimasterslave
-Master-Slave
-Multimaster
Suppose you have the following code:
void InsertNode(tNode** node, int i){
if(*node == NULL){
*node = new tNode;
(*node)->pLeft = NULL;
(*node)->data = i;
(*node)->pRight = NULL;
SetRootNode(node);
return;
} else {
if(i < (*node)->data)
InsertNode(&((*node)->pLeft), i);
if(i > (*node)->data)
InsertNode(&((*node)->pRight), i);
return;
}
}
void Func(tNode **node){
if(*node!=NULL){
Func(&(*node)->pLeft);
tNode *temp;
temp = (*node)->pLeft;
(*node)->pLeft= (*node)->pRight;
(*node)->pRight = temp;
Func(&(*node)->pRight);
}
}
void traverse(tNode** nd){
if(*nd!=NULL){
traverse(&((*nd)->pLeft));
traverse(&((*nd)->pRight));
std::cout<<(*nd)->data<<std::endl;
}
}Let the input given be
98,15,100,10,78,120,5,12,96,110
What would be the output of the following code snippet?
int main(void) {
tree *bT = new tree;
int i = 10;
int data;
while(i--){
std::cout<<"Enter the node"<<std::endl;
std::cin>>data;
bT->InsertNode(bT->GetRootNode(), data);
}
bT->Func(bT->GetRootNode());
bT->InsertNode(bT->GetRootNode(), 99);
bT->Func(bT->GetRootNode());
bT->traverse(bT->GetRootNode());
}Options
-5,10,12,15,78,96,98,99,100,1
10,120
-5,12,10,99,96,78,15,110,120,
100,98
-5,10,12,15,78,96,99,98,100,1
10,120
-98,100,120,110,15,78,96,99,1
0,12,5
(MYSQL question)
I need to compare 2 columns in a table and give 3 things:
1. Count of rows checked.
2. Count of rows matching.
3. Count of rows different.
I've been able to get just rows matching using a join on itself, but I'm unsure how to get the others all at once. The importance of getting all of the information at the same time is because this is a very active table and the data changes with great frequency.
There is integer array like {1,2,4,5,6,1,2,4,3,5,7,2,1}. I want to find the possible combination of pair which sum is 4.
input : {1,2,4,5,6,1,2,4,3,5,7,2,1}
output : {1,1,2}, {2,2}, {3,1}, {1,2,1}...etc which make the sum as 4
Compress a list of words into the shortest string that contains all the words.
Input:
testing
ginger
german
minutes
Output:
minutestingingerman
code up a system that will accept a series of telephone keypresses and return a list of possible names from a supporting data structure. Describe both the data structure and the insert and search methods
Write a program to remove fragment that occur in all strings,where a fragment
is 3 or more consecutive word.
example :
input::
s1 = "It is raining and I want to drive home.";
s2 = "It is raining and I want to go skiing.";
s3 = "It is hot and I want to go swimming.";
output::
s1 = "It is raining drive home.";
s2 = "It is raining go skiing.";
s3 = "It is hot go swimming.";
removed fragment = "and i want to"
i was told that this program will be tested again large files( in example above string are given as a sample)
and then we have to remove fragment from files.so efficiency will be taken into consideration.
Assumptions:Ignore capitalization ,punctuation. but preserve in output.
I told him that i will map the fragment from first string and then search the others, and we actually need to consider 3 length ones only as a 4 length one will implicitly contain two 3 word phrases and the phrases can overlap.
i was stuck when he gave me this kind of example
a a a a a b c b c b c b c
if we are removing fragment "a b c" ,then after removing middle one we got another "a b c" fragment and so on...
There is huge data (numbers) spread across N machine,
Given the median of data all individual machines (e.g. median1, median 2 ... medianN); find the median of all data (i.e. combined median of all data on all machines).
Given 2 dimensional sorted array(Both row and column wise sorted) write a efficient code to find median.
Fill in the blanks:
-- -- -- H I K L M N T
-- -- -- G J O P Q R Swhat is the advantage of using threads in case of single processor system, if the alternative single thread process is an interactive one i.e. it is responsive throughout its execution.
write test cases to test a program given to check whether two numbers are anagram or not.
given a binary tree, write a code to update each node with the sum of values of its subtree.
given a 2 dimensional array with elements sorted in increasing order both row wise and column wise..write the code for an efficient algorithm to search for a particular element.
What is wrong with the following code
char * test(int v)
{
char buf[6+1];
switch(v)
{
case 1: strncpy(buf, "Case 1", sizeof(buf));
case 2: strncpy((buf,"Case 2", sizeof(buf));
case 3: strncpy((buf, "Case 3", sizeof(buf));
case deafult: strncpy((buf, "Default", sizeof(buf));
}
return &buf;
}
int main()
{
char * p = test(2);
cout << p << endl;
}
Now one obvious answer is that they are trying to return address of a local variable. Then the question is how to solve this problem without changing the prototype of the function. Global variable and static variable are not the right answers
Given two sorted arrays of sizes N,M (N > M).
N has M gaps even though it is sorted. (gaps can be in between . Not required to be at the end).
Best algorithm to merge these two arrays , with out using any extra space.
given N people. one person can like one or more than one persons. But not mandatory to like any one. Find leader in that N people. Leader is a person , who is being liked by all , but he should not like any one else.
Idea I have is:
ex: lets assume set is A,B,C. A likes B,C. B likes C,A. C don't like any one.
Create an array of N and initialize to zero.
Now for every like to other person , decrement the corresponding value , and increment the liked person value.Now at the end , the index whose value is N-1 , will be leader.
In now example
step 1 arr[3] = 0,0,0
step 2 (a likes b , c) = -2,1,1
step 3: (b likes a and c) = -1 (-2 + 1 (because being liked by b),-1 (1 -2 (likes two people) , 2 (1 + 1 (being liked by b))
-1,-1,2.
So here C is the leader.
Please discuss if there are any flaws or abt better ideas.
sum the linked lists
1->2->3
4->5
result is 1->6->8
The glasses are arranged in the following order
1
2 3
4 5 6
7 8 9 10
....................
....................When you pour liquid into the 1st glass if it's full, then the extra liquid would be flown into the glasses 2 and 3 in equal quantities. When glass 2 is full, the extra liquid would be flown into 4 and 5 and so on.
Given an N liters of liquid and capacity of each glass is C and the number of levels of glasses is L. Give the amount of liquid present in each glass if you empty N liters of liquid by pouring into glass 1.
Given an inorder traversal only for a binary tree (not necessarily a
BST), give a pseudo code to generate all possible binary trees for
this traversal sequence.
Firstly, how many binary trees can be generated given an in-order
traversal? I know that given 'n' nodes, number of BTs possible is
(2^n)-n. But if we are given a specific in-order sequence, can we cut
down on this number?
You are given two numbers in the form of linked list.Add them without reversing the linked lists. linked lists can be of any length.
Ex:123 1->2->3
10234 1->0->2->3->4
ans: 10357 1->0->3->5->7
You have n strings with their lengths. You are given an add(string s1,string s2) which would concatenate the string s2 with s1 and return s3. Optimize the cost of concatenation of all these strings into one big string.
Ex: 1,3,2 are the lengths of given strings.
1+3=4
4+2=6
total cost=10
Optimize this total cost?
Given: Suppose balanced binary tree(T) is given.
Def'n: sum of the tree is defined as sum of the values of all it's nodes.
Question: Write a method which returns sub-tree whose sum is maximum.
You have a room-full of balances and weights. Each balance weighs ten pounds and is
considered perfectly balanced when the sum of weights on its left and right sides are
exactly the same. You have placed some weights on some of the balances, and you have placed
some of the balances on other balances. Given a description of how the balances are arranged
and how much additional weight is on each balance, determine how to add weight to the balances
so that they are all perfectly balanced.
There may be more than one way to balance everything, but always choose the way that places additional weight on the lowest balances.
The input file will begin with a single integer, N, specifying how many balances there are.
Balance 0 is specified by lines 1 and 2, balance 1 is specified by lines 3 and 4, etc...
Each pair of lines is formatted as follows:
WL <balances>
WR <balances>
WL and WR indicate the weight added to the left and right sides, respectively.
<balances> is a space-delimited list of the other balance that are on that side of this balance.
<balances> may contain zero or more elements.
Consider the following input:
4
0 1
0 2
0
0 3
3
0
0
0
Balance 0 has balance 1 on its left side and balance 2 on its right side
Balance 1 has balance 3 on its right side
Balance 2 has three pounds on its left side
Balance 3 has nothing on it
Since balance 3 has nothing on it it is already perfectly balanced, and weighs a total of 10 pounds.
Balance 2 has no other balance on it, so all we need to do is balance it by putting three pounds on its right side. Now it weighs a total of 16 pounds.
Balance 1 has balance three on its right side, which weighs 10 pounds, so we just put 10 pounds on its left side. Balance 1 weighs a total of 30 pounds.
Balance 0 has balance 1 on its left side (30 pounds), and balance 2 on its right side (16 pounds), we can balance it by adding 14 pounds to the right side.
The output should be N lines long, with the nth line listing the weight added to the nth balance, formatted as follows:
<index>: <weight added to left side> <weight added to right side>
So the output for this problem would be:
0: 0 14
1: 10 0
2: 0 3
3: 0 0
Rotate a n*n (square) matrix by 90 degrees.
You are given a list of points in the plane, write a program that
outputs each point along with the three other points that are closest
to it. These three points ordered by distance.
The order is less then O(n^2) .
For example, given a set of points where each line is of the form: ID
x-coordinate y-coordinate
1 0.0 0.0
2 10.1 -10.1
3 -12.2 12.2
4 38.3 38.3
5 79.99 179.99
Your program should output:
1 2,3,4
2 1,3,4
3 1,2,4
4 1,2,3
5 4,3,1
Implement a single-word division:
i.e., you are given a long integer X having 'n' limbs (32-bit words) and you need to divide X by another 32-bit int 'b'
optimize your solution for time. Can you do this better if you know that 'b' divides 'X' exactly ?
what if 32-bit division on the target architecture is expensive ? try to minimize the # of integer '/' and '%' ops (e.g., using floating-point tricks)
Ph.Intvw 2
coding: find a given value/node in a BST
node find(node *n, int x)
follow up :
find a value that is closest (arithmetically) from a given value/node, same signature as above
Ph.Intvw 2
write code to calculate number of words in a large text file
file i/o language specific implementation details not required
what are the corner cases? cover all the corner cases like beginning/ending with space, multiple spaces etc
Ph.Intvw 2
Modify the Stack DS to implement constant time Min lookup
Ph.Intvw 2
OODesign: Design a parking lot
Ph.Intvw 1
Write code to print all the paths in a binary tree, whose values sum up to the value given
root and the sum given
signature: void sum (Node *node, int sum)
follow up question: now change the algo to the same thing for any arbitrary path
arbitrary path: can start from anywhere (not necessarily root) - can end anywhere (not necessarily leaf)
Ph.Intvw 1
What data structure will you use to design a phonebook
What is its time complexity for retrieving, adding etc
right answer: a hashtable with key contactname and value being the head pointer to a list of contacts with that contact name [multiple contacts with same name]
Ph.Intvw 1
What happens when you do www.amazon.com
what exactly happens at the dns server, etc etc, details of the protocol used ….
wanted all the details
You have to design a system for finding the run time puncture of a car. Give a robust and simple design.
During my 2nd interview
1. Use 2 stacks to create a queue structure
2. If you have a tree how to verify it a BST
A. User the inorder traversal
3. Write a code to implement above question 2.
Given a large buffer which contains almost infinite number of words. You are given an API "char* getNextWord(int* len)". You need to find all the words & their frequency in the buffer.
For eg. char* buff = { "I", "AM", "Programmer", "AM", "I", "Boy" ....}.. then
Output = I = 2, AM =2, Programmer =1, boy =1.
Check weather a tree is a sum tree ...
Sum tree is a tree whose root value is equal to the sum of its adjecnt children
given a 10 digit number,find the greatest continuous 4 digit number.
Ex:9164352435
Ans : 9164
I want to build a system with the following APIs :
1. put(n) - stores data in the system
2. get() - will give me the element added the first and so on.
I gave a queue implementation using the LinkedList (using a head and tail pointers). Interviewer asked the complexity of both put and get operations and asked how I would implement "removeElement(n)" - now, given a linkedlist/array implementation of a queue, removeElement(n) is going to be O(n) worst case operation, I could not find any other options.
How to find Hexadecimal for a 32-digit integer
From two lists/arrays find duplicates. I gave two answers :
1. Sort them both O(n log n)
2. Use a hash table with key as the number in the array and a counter to increment occurences. O(n) to traverse both lists and increment the counters in the hashtable -
Reverse n-Ary Tree and Return List of Leaf Nodes as Output
example
Tree will be like
1
/ | \
2 3 4
/ / \
5 6 7
/ \
8 9
out put will be 1st reverse the tree e.g. 2 points to 1 , 5 points to 2 , 8 poinst to 5 and so on for each node , without modifying the tree and then return list containing leaf node
as OutPut Head-> 8->3->6->9->NULL
do it efficiently , i saw a approach & code here but i think its not correct , guys can you make it correct ?
why is string immutable?
Implement level search in a binary tree.
Life cycle of servlet
You are given a binary Tree B and pattern p = LLRLR. Let S = ppppp… be a sequence generated from the given pattern p. If ‘L’ denotes left traversal to node from its parent node and ‘R’ denote right traversal to node from its parent node find in B the largest of all such sequences.
Note: Only the Head will have neither 'L' or 'R'
An easy way is to record a path till you reach a NULL node and search for S in the recorded path, but that would be an O(n^2) algorithm, you are expected to give an O(n) algorithm where n denotes the number of nodes in B
Your algorithm should cater to all possible patterns.
Given two integers a and b. Find the value of a/b without using division or modulo operators in C/C++.
I tried with repeated subtraction of b from a, but the interviewer felt that this approach is inefficient. Any better approach ?
Code merge sort
How will you test this function
Talk about sorting algorithms.
Explain quick sort and merge sort in details
Write a function which takes an integer and returns the number of '1' bits in its binary representation.
How will you test this function
A binary string, of length N, is considered dangerous if it has 3 or more 0's adjacent to each other. Given N, how will you
1. Compute the number of dangerous binary strings of length N.
2. List them.
Examples
N = 3 --> only one string 000.
N = 4 --> 3 strings, 1000, 0000, 0001.Find the longest Zig-Zag path in a Binary TREE
Given a set of n symbols a size k and a combination of length k of non repeating characters from the symbol set write only an ITERATIVE algorithm to print the next unique combination.
Ex: Symbols =[1,2,3,4,5]
size = 3;
given combination = 123, result = 124
given combination = 254, result = 312.
Given a large document and a short pattern consisting of a few words (eg. W1 W2 W3), find the shortest string that has all the words in any order (for eg. W2 foo bar dog W1 cat W3 -- is a valid pattern)
Write a program to find the mirror image of a binary tree?
if a tree is like
01
02 03
04 05 06 07
The mirror will be like
01
03 02
07 06 05 04
There are n steps in a hill. You stand on the top, you can climb down either one step or two steps at a time. Find the number of paths by which you can reach the bottom?
write a program to find the vertical sum of a binary tree?
if the tree is like
01
02 03
04 05 06 07
vertical sum is 04 02 12 03 07
Find Least common ancestor for multiple nodes in a binary tree.
node* FindCommonAncestor( node* root, key* keys, keys_length)
Implement stack class, algo for returning minimum number. what is Thrashing, Explain deadlocks.
Remove duplicates from string given " bananas " Return "bans"
Write code for both O(n) and O(n2) solutions
Return k most frequently occuring numbers from a file of very large size containing numbers.
Give complexity. how your solution will solve scalability issues.
How do u represent n-ary tree in a integer array,
Write routines for serialize and deserialize n-ary tree.
give the number of integral solutions of the following equation:
x[1] + x[2] + ... + x[k] = Nwhere x[i] are non-negative integers and k <= N
A sequence of numbers is called a zig-zag sequence if the differences
between successive numbers strictly alternate between positive and
negative. The first difference (if one exists) may be either positive
or negative. A sequence with fewer than two elements is trivially a
zig-zag sequence.
For example, 1,7,4,9,2,5 is a zig-zag sequence because the differences
(6,-3,5,-7,3) are alternately positive and negative. In contrast,
1,4,7,2,5 and 1,7,4,5,5 are not zig-zag sequences, the first because
its first two differences are positive and the second because its last
difference is zero.
Given a sequence of integers, sequence, return the length of the
longest subsequence of sequence that is a zig-zag sequence. A
subsequence is obtained by deleting some number of elements (possibly
zero) from the original sequence, leaving the remaining elements in
their original order
Twisted linked list problem: Two linked lists merge at some node p,both the head pointers are given find the merging point under
the following restrictions.
1. You should not traverse to the end any of the linked list.
2. Merge node p should be detected by the time you reach at most most k nodes from p.
3. Space should not exceed by k units.
4. No saving of nodes to hard discs.
5. No recursion.
given two singly-linked lists with very nasty properties:
first, they merge at some point but, more than that,
their common tail might end up in a loop.
find the position where the two lists merge
Find and store all the valid numbers in an array that are in the string including negative, positive, hexadecimal, octal, binary?
For example string "abcd 0xa 11.12 123" has values 10, 11.12 , 123.
I would rephrase the question: find all words(separated from other words through tabs or spaces) in the string that can be expressed in the form of decimal number. After the words are obtained store their value in the array.
Given a set of n symbols and a size k write only an ITERATIVE algorithm to print all possible permutations of the given symbols with respect to the size given.
For example: Given symbols ={'A','B', 'C'} and
size = 2;
Solution is {AA,AB,AC,BA,BB,BC,CA,CB,CC} and count = 9.
Do not give recursive algorithm here
If pairwise sums of 'n' numbers are given in non-decreasing order
identify the individual numbers. If the sum is corrupted print -1
Example:
i/p:
4
4 5 7 10 12 13
o/p:
1 3 4 9
Example: N = 4, Say numbers are a, b, c, d. The input is: pairwise sums in sorted order, i.e. values a+b, a+c, a+d, b+c, b+d, c+d are given sorted order
We have to find a, b, c, d.
Given the head of a Binary Search tree, trim the tree, so that all elements in the new tree returned are between the inputs A and B
get a date(mon/day/year) from user. Print exact the week of dates(Sun to Sat)
ex) input: 2/20/2001 if the day is Wednesday
output: Sunday 2/17/2001
Monday 2/18/2001
Tuesday 2/19/2001
Wednesday 2/20/2001
Thursday 2/21/2001
Friday 2/22/2001
Saturday 2/23/2002
get a string(word) from user, then make every possible permutation words.
Ex)intput: tree => output : tree, rtee, rete, reet, etre, eetr, eert, eter, eret, teer, reet...
Average of Nodes in tree.
Given an array-based heap on n elements and a real number x, efficiently determine whether the kth smallest element in the heap is greater than or equal to x. Your algorithm should be O(k) in the worst-case, independent of the size of the heap.
write an algorithm finding the no.of one bits from 1 to n,for given any n value.
complexity should be good
example:
1=1
2=10
3=11
4=100
5=101
6=110
.
.
if n=3 then ur answer is 4
if n=6 then ur answer is 9
Interviewer is looking for an algo in O(log N)time complexity
why do we need to pass address of the objects as an argument in copy constructor
Rounding of an matrix:
it is a 2-d matrix of double values such that the sum of any row or coloumn is integer.floor or ceil every array element so that sum of any row or coloumn remains same.
Given an array of unsigned integers which is initially increasing (value of integers)and then decreasing find the maximum value in the array
Given an array of elements find the largest possible number that can be formed by using the elements of the array
eg: 10 9
ans: 910
eg: 2 3 5 78
ans: 78532
Given an array of integers, find the longest subsequence of elements which monotonically increases. for ex. array = {1 4 8 2 5 7 3 4 6}, the longest subsequence = {1 2 3 4 6}
I have explained him about O(N^2) with O(1) space algorithm but the interview is expecting O(N log N). Could any one help me explaining the algorithm in detail ?
Write a programme to produce all permutations of a given string where
characters are not unique. That means you are not allowed to print the
duplicate strings.
Ex:
If input is aaa
The output should be only aaa
Given an array that contains only the three digits 0,1,2, how will u
sort in one pass?
Design mine-sweeper .
What is Hashing.
There is external file with 5billion numbers..how will u sort
Wht if 1billion pairs?
Have 5million key-value pairs wht datastruct u will use?
What does public static void main means ..how it is called?
Wht is oop and comparision with traditional method.
Wht is abstraction?
Diff bet abstract class nd interface nd when u use one?
give an algorithm for finding duplicate parenthesis in a expression.
(( a + b ) * (( c + d )))How would you design and implement a large social network's (G+ or fb) friend recommendation system ?
Write a program that reads a file containing a sorted list of words (one word per line, no spaces, all lower case), then identifies the longest word in the file that can be constructed by concatenating copies of shorter words also found in the file.
For example, if the file contained:
cat
cats
catsdogcats
catxdogcatsrat
dog
dogcatsdog
hippopotamuses
rat
ratcatdogcat
The answer would be 'ratcatdogcat' - at 12 letters, it is the longest word made up of other words in the list.
Given n points in 2 dimn space where x and y coordinate of each point is between the range of 1 and 1000. Now for any given point find all the points whose distance is less than or equal to 5 from the given point.
Consider a Linked List with each Node, in addition to having a 'next' pointer also has a 'random' pointer. The 'random' pointer points to some random other Node on the linked list. It may also point to NULL. To simplify things, no two 'random' pointers will point to the same node, but more than 1 Node's random pointer can point to NULL.
Now we are required to reverse the direction of all the pointers (both the 'next' and 'random') of the Linked list. The constraint is the solution MUST be O(1) space complexity (A constant number of new nodes can be created but not proportional to the length of the list)
How would you retrieve values in a given range from a hash table. What is the complexity? and What other data structures you can use to make it a efficient one?
Suppose: input: 1, 3, 4, 5 , 6
Range: 1, 5
Output: 1, 3, 4, 5
Is tree a good option?
Given a very long list of URLs, find the first URL which is unique ( occurred exactly once ).
I gave a O(n) extra space and O(2n) time solution, but he was expecting O(n) time, one traversal.
Asked few times over phone and in-person.
Asking to get my facts correct and consolidate the info for me and for everyone here.
How's synchornization differs in multi-core vs multiprocessor arch?
Little internals about them.
How the code design and implementation changes for these two arch?
pour in your suggestions and any nice read if u know any.
For those who get bored of sorting/hashing/string manipulation problems, here is the geometric one:
Given n lines in the plane (for simplicity assume no
3 lines intersect at one point).
Count the total number of triangles in the plane created by these lines.
Observe that smaller triangles may be part of larger ones.Look here for example:
h t t p://farm8.staticflickr.com/7021/6465828833_15e7447992_z.jpg
A stream of 1's and 0's are comming .At any time we have to tell that the resultant number from the binary digits till that point is divisible by 3 or not .For eg: let's see one example.Let 1 come (not div by 3) .then 1 come so resultant binary number is 11(3) which is divisible by 3 , then 0 come make it to 110(3) which is divisible by 3, then 0 come make it to 1100(12) which also divisible by 3 .
A BST of integers is somehow serialized into a file in pre order. File is too large to bring into memory at once. Find height of the BST. Just give a procedure no code
Given a BST and two values m and n . We need to find out all the nodes whose values are in range of m and n .
There are 100 prisoners , and a officer of them . Now the officer gave the command to the prisoner that next day they will be going to wear a hat which they will not be know its colour . But its colour will be either Red or Blue . And he says that all the prisoner will be standing in a line . And then the officer will start asking the color of the prisoner one by one from the back . whichever prisoner says the wrong color of his hat ,gets shoot .So now we have to find out wat strategy should the prisoners should apply to safe maximum prisoners .
In a plane we are given latitude,longitude coordinate , and we are also given a point(having lat,long value) . We need to find out the nearest point , in most efficient way .
Find all the permutation of the given string ? But take care of duplicate characters .
The sorted array is rotated by some factor . And we need to search a key .?O(logn) ?
Random pointer is present in every node of the linked list . And they will be pointing to any of the node of the list . We need to clone this list and return it .
Edit Distance ?
Print the M*N matrix in spiral way .
Given a Node in a binary tree . We need to find out all the nodes at K distance fron that node .
There is a Directory in which there are subdirectories and recursively have subdirectories . We need to find out is any subdirectory is pointing to its any of its ancestor .
Given a m*n matrix and a person is sitting in (0,0) box, and he has to go to the (m-1,n-1) box of the matrix .And the person can only go to right or down box from its current box position . We need to find out the number of ways he can reach from start to destination box .
The string "PAYPAL IS HIRING" is written in a zigzag pattern on a given
number of rows like this: (you may want to display this pattern in a
fixed font for better legibility)
P A H N
A P L S I I G
Y I R
And then read line by line: PAHNAPLSIIGYIR
Write the code that will take a string and make this conversion given a
number of rows:
String convert(String text, int nRows);
convert("paypalishiring", 3) should return "pahnaplsiigyir"
Print every level in a tree in its own line. Its a modified version of Breadth First Tree traversal.
Write a method to test if a String is number.
Check for all the cases like '.', '-', '+' ascii values multiple occurance of sysmbols.
Objective: Cover all the use cases
Convert and infix expression to postfix expression
Write a function to reverse a UTF-8 encoded string in-place.
Write a code to find out endness of a system?
(I am a java guy).How can we do it in java?Do we need to take care of endness in java?If yes give exmaples of such situation?
Given a binary tree print the largest part of binary tree that satisfies the property of BST.
Why linux is more stable than windows ?
what are the stuffs a compiler provide to a class ?
Write a code snippet print a count no of characters in a number (string can't be used) ?
int count(int num)
{
//code should return no of digits
}
What is the disadvantage of normalization ?
Why can't we follow normalization always ?
What is critical section ?
Write an algorithm to avoid and detect deadlock in C++ ?
What is Banker's algorithm ?
There is a pool of memory with a specific address. How to make sure the object is always created in that part of memory ?
How to forbid the creation of object in
1>Stack
2>Heap
?
How to restrict a function so that in can't throw any kind of exception ?
How to restrict a function so that it can throw the exception of a particular type ?
Process vs Thread
Can trigger be used with select statement?
Design an API for Deck of Cards
Difference between notify() and notifyAll()
Given an unsorted array and a number a, find a pair of numbers(b,c) from the array sch that
a=b+c.
WAP in Java to create deadlock
Soft Skill question:
Where do you think Amazon can improve customer's experience? Explain how!
Open ended question:
You have to design lifts for a 75 floor building. How many lifts would you install ?
Given a function bool which return 1 with probability p and 0 with probability 1-p.How will u design a function to simulate the toss of a coin using bool.The function should return heads or tails with equal probability?
Why was multiple inheritance not included in Java though it was previously in C++?
A number is qualified is all its digits are in ascending order. Example: 123; 1<2<3. Given the value on N, the number of digits in the number, print all the qualified numbers.
Given an image that is represented by Nx1000 matrix of binary numbers. 1 represents black(image ink) and 0 represents white(blank).
The page breaks are applied in two ways:
1.)Find the row with all the white pixels.
(But this selection should be efficient as we want to print in minimum no. of pages.
For example: if we get a white line on 200th row, 600th row and 900th row, we should choose 900th line to break page).
2.) If no such row exists, break on the 1000th line.
Return all the positions of the pixels where you break the page and the number of pages, so that the image can be printed in the minimum number of pages.
How do you find a shortest connection between two persons on Facebook(if the same exists)?
You are provided with an API which returns the list of friends of a particular persons
SMS Problem
1 - NULL, 2 - ABC, 3 - DEF, 4 - GHI, 5 - JKL, 6 - MON, 7 - PQRS, 8 - TUV, 9 - WXYZ, * - <Space>, # - <Break>
We must convert the numbers to text.
Eg
I/P - O/P
22 - B
23 - AD
223 - BD
22#2 - BA (# breaks the cycle)
3#33 - DE
2222 - 2
2222#2 - 2A
22222 - A (cycle must wrap around)
222222 - B
You have a class MyObject. What is the difference between the following statements::
1) MyObject foo;
2) MyObject *bar;
3) MyObject *foobar = new MyObject();
Write a function for pow(double a,int b)? Prepare floating point intricacies in java...
How to design a good hash function if the key is a person`s name
There are 10 boxes of apples. Each apple in the boxes weights 1 pound, except that one of the boxes contains bad apples, which weights 0.9 pound each. You are given a digital weight (not a scale), and you can take apples out of the boxes. what is the minimum time of weighs to find out which box has bad apples?
I gave one solution of 3 times using divide and conquer, but the interviewer said that 1 step is possible. So I couldn`t come up with the solution.
Generate all possible unique 4 digit numbers such that no two adjacent numbers are the same and any number starting with 4 should end with a 4 . eg 1234 , 1232 are both correct but 1223 is not .
Given an NxN matrix with unique integers : Find and print positions of all numbers such that it is the biggest in its row and also the smallest in its collumn .
eg : In 3 x 3 with elements
1 2 3
4 5 6
7 8 9
the number is 3 and position (2,2)
Print all the increasing subsequence from the given range 54782369862345 .. ex: 5,7,8,9; 4,7,8,9; 2,3,6,9 ..
What is Height balanced tree ?
Difference between Red Black Tree and AVL Tree ?
There are two arrays.
int arr1[5] = { 3, 5, 2, 5, 2}
int arr2[5] = { 2, 3, 5, 5, 2}
The arrays will be called similar if they contain same number of elements equally.
Write the pseudo code to check this ?
I was not allowed to use sorting and hashtable.
int a[10];
a[-1] = 20;where is 20 stored?
I said this won't compile in C under normal circumstances, he agreed, and then said let's assume C allows this, what happens?? I said maybe then previous local variable of the function will get overwritten with this value.?? Nay insights?
char *p=NULL;
p = (char *) malloc(10);
p++;
free(p)'What happens, is there a leak?? are 10 bytes freed??
I answered yes.
Find the substring of length 3 which is present in the reverse order from the string.
Ex: if the string is abcdcba (cba is the reverse of abc) so we should return cba.
And was asked to improve upon the complexity.
define a struct imitate ip_header as it is in a packet.
actually, he wanted to see how i handle things with aren't a byte long or odd number of bytes long, like flags, ihl, version and all.
what's the best struct to define a ip_header, and tcp header.
write a program to convert char *mac_address to int array.
eg mac_address ="ab:cd:ef:12:34:56" to
result= [ab, cd, ef, 12,34,56]
I was able to do it, but wasn't sure, how do we store hex values in int array. i mean a[0]=a, will essentially be a[0]=10, can we store hex directly in array, so that when we do memcmp or something, we can directly compare hex against hex?
Not sure if me making sense here, still let me know, if you have suggestions.
Given a set of numbers [1-N] . Find the number of subsets such that the sum of numbers in the subset is a prime number.
how to find a duplicate element in an array without using extra memory....do this in O(n)?
Given a doubly linked list containing only three integers 1,2,3. Sort the list without exchanging the values.
Eg- 1->3->2->1->2->3->2->1->1
output: 1->1->1->1->2->2->2->3->3
Given a Binary tree where nodes may have positive or negative value, store the sum of the left and right subtree in the nodes.
Eg-
10
-2 6
8 -4 7 5Output:
20(-2+6+4+12)
4(8-4) 12(7+5)
0 0 0 0Given a number,find the next higher number using the same digits in the number. Eg- 15432, Soln- 21345.
what is the difference web crawling and web scraping?
What is Web crawling?
What is the fastest way print output to STDOUT in Java?
Please tell the code of how to sort a singly linkedlist in C# or C++.
given an integer find the next(smallest number greater than given number) integer which is palendrom
for ex 111 next palendrom 121
301 next palendrom 313
For a stream of insertions and deletions, recall that x[j] = #insertions - #deletions of element j.
Given such a stream satisfying x[j] >= 0 for all elements j, let
A = { j : x[j] > 0 }
Determining whether A is empty is easy: just check if the sum of all x[j]'s equals 0 (which is easily doable in a stream).
Problem: devise a small memory streaming algorithm to determine if |A| = 1.
Extensions: What about higher sizes of A? What if the promise is not satisfied and we define A to be the set of j's with x[j] not equal to 0.
Algorithm to output for a length m of a number stream, the value of the element j appearing in the stream for which freq[j]>m/2 with space complexity O(1) and time complexity O(m). Dont need to worry about the case when there are no elements with freq > m/2.
The question in simpler terms:
In a collection of 'M' elements, some elements are repeated. Find the element which occurred at least M/2 times.
You have two arrays A and B of strings. In the array B all element are from A except one. ex:
A = {"abc", "bcd", "dpr"};
B = {"abc", "mnp", "bcd", "dpr"};
You have find out the string which is extra in B in O(n) time.
In the above example it is "mnp".
There is a very Primitive Database and it has a table say "Travel". The content of table is as follows:
Source | Dest
--------------
Sea | LA
LA | FL
LA | MA
FL | Sea
Sea | FL
The ask is to find out all routes between (Sea) to (FL) with mininum hop.
the Result would be:
1. Sea -> FL
2. Sea -> LA - > FL
You have to write a Middle tier function to achieve above result. You can assume there is DBAPI that return the Destination city if you provide the source city.
How to find out memory leak in a c/c++ program both static and dynamic memory leak.
Give you a number N, print all valid combinations of ( and ).
e.g.N == 1, then print ()
N == 2, then print ()(), (())
N == 3, then print ()()(), (())(), ()(()), ((()))
N == ...
You are given a word and a dictionary. Now propose an algorithm edit
the word (insert / delete characters) minimally to get a word that
also exists in the dictionary. Cost of insertion and deletion is same.
Write pseudocode for it.
Seems like minimum edit distance problem but some modification is
needed.
There are three arrays of numbers A,B and C. You have to find out all tuples <a,b,c> such that a-b = c where a is from A,b is from B and c is from C.
convert a double-precision number to rational, i.e.:
0.125 -> 1/8
don't care about arithmetic overflow
Given an array and a number K. You have to
find out longest subset from the array whose
all pair sum will be greater than k.
ex: {8,3,4,1,6,2,5,7,9} and K=12
ans: {8,6,7,9} or {5,7,8,9}Under which conditions the default assignment operator
is not generated by the compiler for your class ?
(assuming that you do not declare the assignment operator yourself)
You have coins with different denominations and you have limited number of each denominations (some maybe zero), how will you determine if you can supply the given change. DP , are you sure? think again.
You are given 'n' appointments. Each appointment contains startime and
endtime. You have to retun all conflicting appointments efficiently
starttime and endtime can range from a few min to few years.
Explain virtual function, up-casting and applications?
How will you restrict the memory allocated to a program by an operating system ?
Write a function that takes in two arguments, a string and a list of delimiters and gives the output as a list of string seperated by the delimiters where each word takes one space in the list. For example: if string is "How are you, Mr. X?" and list of delimiters is {space, comma, dot} the output would be:
How|are|you|Mr|X?
We have a job sequence like this.
A
/ \
B --C
This case A's dependent jobs are B & C
B's dependent job is C
C's Dependent job is null
If we need to complete any of the steps we should need to complete the dependent object.
This case job sequence will be C->B->A
Can anyone comeup with simple o(n) solution for this?
You have given a file containing sentences. Now you are given a sequence of characters. You have to find the starting location of each word containing one of the permutation of the word.
e.g File - 'She submitted her assignment.' Input Sequence - imt. Since the file contains the word 'submitted' containing the sequence 'mit' which is a permutation of 'imt' So it will return 1. Similiarly it will return for all other words.
How to rotate the array with o(n) or o(nlogn)/
eg) A[]={A,B,C,D,E} rotate Index - 2
It should be {C,D,E,A,B}
output all dates "Fridays, 13th" in the format dd.mm.yyyy starting from 1st Jan 1900 (Monday)
Given a Big XML File. You have to design and implement the Data Structure which stored their keys and its value accordingly in C/C++ language.
Write a Program to Store all the given XML content to your designed Data Structure and Retrive it . Basically SAX/DOM parser :)
Contraints :-
1> Data Structure should not be a flat file type.
2> Every Program code must be modular and each module should not exceed 15 lines of code.
3> No Usage of STL library functions.
4> Each Module should not have return type other than success and failure of operation.
5> Use Memory management at the most.
6> Design and problem approach crutial.
7> Minimal Space and Time Complexity for each code.
8> No Static variable usage and all memory allocation should be dynamic.
9> There are occasion like a parent has more than one child you have to take care of such cases.
10> Handle all possible error condition.
How you will test a random number generator?
Assume we have a sorted list of document_id-s for every keyword. Given a search string, how to find the documents that have all keywords in the search string? Basically how to find the intersection in a set of sorted arrays? What is the complexity? How to improve if there are only two arrays and one is much smaller compared to the other? How to distribute this on a set of different machines?
Given an array A[], find (i, j) such that A[i] < A[j] and (j - i) is maximum.
Given a large file of integers, how to compress the file so that we can also do search efficiently?
Given a positive integer N, arrange the integers 1 to N such the position of the average of two numbers (if present) falls outside the two numbers. For example, for a[i] and a[j], if b = (a[i] + a[j])/2, then if a[k] = b, k < i or k > j.
Hint :- If the average of two numbers is not an integer then we can assume that they do not have an average.
Implement a RandomAccessContainer and its iterator in C++, like std::vector
4 subjective questions.
Implement blocking queue
Explain Producer Consumer
how to design tweeter like application.
20 objective based on pattern of SCJP exam. easy
A forgetful professor wants to know the names of all the students in a class of strength 'n'. For this, he makes 'm' students stand up at a time. He remembers the names of all the students who are standing and the ones who are sitting but doesn't remember the name of each student individually. He does this operation 'k' number of times and tries to infer all the names. What can be the value for 'k' when n=13 and m=5
come up with a solution, where u r given a single pointer in a single link list and u shoudl be able to return (+/-)nth node from it.
My solution:
list * returnN (list *node, int n)
{
if (n>0) {
traverse and reverse list from node to nth node
} else {
traverse and negatereverse from node till nth node
}he asked for algo only, so this worked fine.
eg list=1->2->3->4->5
returnN(1, 3)
output 4
list=1<-2<-3<-4->5
returnN(4, -2)
output 2
list: 1<-2->3->4->5
Any other suggestions??
Write an algorithm to find an element in an 2D array such that the element should be maximum in the row and minimum in the column?
One another question given two arrays A[i[ and B[i] print the product such that B[i] = A[0] * A[1]...A[i-1] i.e other than its position all products
Algorithms can be use a kind of additional storage to figure out pre prods - from i to i-1 and from i+1 to i and then combine
Division wasnt allowed !!!
Question on printing the string equivalent of an integer number
To build a tree expression - (1 +3) * 4 - all numbers and operators are nodes in a tree. Was a reversal tree I guess....wrote my custom logic
How to print given Number in word(Example: 9995 should be printed like "Nine Thousand Nine Hundred ninety five")
How to prints all possible permutations of "TURING"?
Given a linked list of size n and natural number k<n. Convert this list into a new list like this. Reverse the elements in the group of k starting from the first and link these reversed subsets of length k such that the tail of the first is linked with the head of the second then the tail of 2nd is linked with the head of 3rd and so on. The head of the first would be the start of the list.
Eg:
Original linked list:
1->2->3->4->5->6->7->8->9->10->11
Here n=11
Given k=3 the new list should look like this:
3->2->1->6->5->4->9->8->7->11->10
Here first the elements are divided into groups of k starting from the first like this:
G1=1->2->3, G2=4->5->6, G3=7->8->9, G4=10->11
After reversing
G1=3->2->1, G2=6->5->4, G3=9->8->7, G4=11->10
Then combine them like this:
3->2->1->6->5->4->9->8->7->11->10
Given a matrix of size m*n of all entries either 0’s or 1’s. You have to travel from bottom left to top right corner in the matrix. You can only walk on the cells with 0’s in them and can move only up, down, left or right i.e the cells with 0’s are free cells and with 1’s are blocked and you can’t move diagonally. Find the shorted path from bottom left to top right corner in the matrix and also report if there doesn’t exist any such path.
Write a MergeSort for Two Different Sorted Link List.. Emphasis on TO and SO with all Error Conditions...
there are N members in a team. You have given a schedule of meetings for each member like startTime and finishTime. business hrs are given e.g. 8-18. Now you have to arrange a meeting for D duration such that all of the members can attend the meeting without conflicting with their schedule.
For e.g.
No. of members in the team=3
each members meeting start time and finish time are:
M1 - 8-11
m2 - 12-15
m3 - 15-18
business hrs 8-18
meeting duration 1 hrs
then the meeting slot can be 11-12 when all members are free.
if meeting cant be arranged between business hrs then return "meeting cant be arranged".
2. write sizeof operator.
I gave the code as
#define sizeof(data)
{data *p=0; size = abs((p+1) - (p))He was fine with this.
But then how would we extend this to find sizeof of variables???
PS: sizeof in C that we use works well for both datastruct and variable.
what is the return value of the function that returns int, but isn't returning anything explicitly.
for instance output of
int fun()
{
printf("\ncrap");
}
void main()
{
printf("\n return value of fun %d", fun());
}i said, should be exit status of 0(success) or value in EPI register, but looks like i wasn't corret. He said, this has something to do with stack unwinding??
Any insights?
An efficient way to convert Binary tree to BST?
convert the same tree to BST.
One integer array. One Element has even number of occurences and all others have odd occurences. Return the element which is present even number of times
Convert a character string into a value based on the radix or base.
Input parameters:
1. char *str such as "3523" (in decimal),
"11001" (in binary),
"a1f38c" (in hex)
2. radix or base(such as decimal:10, binary:2, hex:16, octal:8)
Return: integer value (not unsigned) that is calculated based on the input string and radix or base.
for example: string is "343432" (base 10): return value 343432
string is "10010" (base 2): return value is 18
string is "a1b" (base 16): return value is 187.
Tell the algo and write a program?
We have a N X N matrix whose rows and columns are in sorted order. How
efficiently can we find
the median of those N^2 keys ?
Design the system for threater reservation system. for example Seat or chairs are organized in the form of rows and columns. When the first person come and book the ticket need to provide a seat on the middle of the last row. When next person come we have to provide empty space between the existing audience and book the ticket for the set of people. How we will design this system?
In a nxn matrix, data provided like below. We need to find the groups of 1s with the adjustent column and row.
eg)
0 0 0 0
1 1 1 1
0 0 0 0
group of 1 is 1
1 0 0 0
0 0 0 1
1 1 0 0
group of 1s is 3
Any thought how to get the set of groups.
there ar two points A and B. The coni is being tossed at A and the outcome is being stored in a string like "HHTHHHHHTTTTT...", where H = Head, T = Tail; Now we have to send this information to point B by using minimum bandwidth?
Do it in minimum space ?
why java is called object oriented language?
#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>
#include <functional>
struct base
{
int val ;
base() : val(100) {}
virtual int foo() { return val ; }
} ;
struct derived : public base
{
double val ;
derived() : val(200.2) {}
virtual int foo() { return val ; }
} ;
int main()
{
std::vector<base*> vec( 3 ) ;
derived derived ;
std::fill( vec.begin(), vec.end(), &derived ) ;
std::transform( vec.begin(), vec.end(),
std::ostream_iterator<int>( std::cout, "+" ),
std::mem_fun( &base::foo ) ) ;
return 0;
}
what will be the output of the code above
How would you design a class for a wrist watch?
where the local,global variables are stored heap,stack,data segment,code segment??
mr bobo walks to a store with coins of some denominations.he purchases some things from the store such that the total price comes out to be x. mr bobo being extremly lazy man doesn't want to handle too many coins,so he decides that he is going to pay the shopkeeper only with 3 coins i.e., if any 3 or less coins sums upto x ,he will pay the shopkeeper. also being the miser he doesn't want to pay even extra penny. if he doesnot find 3 such coins he will drop the baggage.
input:
totalprice
no.of coins
denominations
output:
we have to set output as upto 3 coins in increasing order of denomination if you find.
if no combination possible output is single array with element -9999
Ex:
TotalPrice = 100
no.of coins = 5
denominations = {10,30,40,50,70}
output1 = {30,70}
int output1[100];
void GetCoins(int totalPrice,int noOfCoins,int denominations[])
{
//Write code here
}
Wht is 'volatile' in c?
write a function that given two strings s1 and s2, it will return s1 Minus s2, and it has to use same s1 location.
ex: s1 = "abcdB" ,s2 = "b" ,s1 Minus s2 = "acdB"
give a *recursive* algorithm to print all permutations of 'n' consecutive integers in lexicographic order, i.e.:
1 2 3 4
1 2 4 3
1 3 2 4
...
4 3 2 1
How do you Design Access Specifier in C.
Given pointer
char *p = <body> <tagname1>Tagvalue1</tagname1>
<tagname2>Tagvalue2</tagname2>
<tagname3>Tagvalue3</tagname3>
..
..
..
<tagnamen>Tagvaluen</tagnamen>
</body>
Write a Program to replace a Tagvalue from existing Value to User Provided New Value..
example : - Your Function Func(TagName,New tagvalue) should replace the existing tagvalue of the Tagname to NewTagName..
Given Constraints :-
1> Function should be granular enough.
2> Its actually a design question so approach is important.
3> Take Care of Error Condition . Like TagName not found etc.
4> Also make sure the conditions like if the Given Tagvalue is not of Same Length that proper handling etc.
Design the XML Parser.
Given a stream of billion numbers, find the smallest million numbers.
Later was asked about map reduce and memory management questions related to the previous question.
Design minesweeper game.
complete object oriented design.
Design LRU cache.
explained both java design(linkedhashmap) and c++ design(using hashtable and linked list)
Design a web crawler.
Find an union of 2 sorted sets. was asked to write the code.
# include<stdio.h>
main ( )
{
int i=1;
printf("%d %d %d",i,i++,++i);
}
The answer is 3 2 3.
Please explain
Write a program to convert a BST to sorted list. You must use the same tree and make the right child pointer as the next pointer in the list.
I think I flunked this one.
How to find the strength of a pair of similar eggs given a N story building.
I explained the divide and conquer approach. He expected better.
Develop a hashing algorithm for strings.
I replied saying MD5 hashing and converting the hash to a BigInt implementation.
How to merge K sorted arrays into one array.
I explained the second part of external sort and said its in O(N logK). I don't think he understood the time complexity I explained.
How to find a number in a rotated sorted array.
He was looking for the binary search kinda solution
Test cases for chat application (lyk MSN ,YAHOO CHAT,GTALK etc).
Question 3)
Given an crypted array obtain the original text . Should be implemented without extra space .
Eg: Crypt array : a3b4c3
decrypt array : aaabbbbccc
Imagine the array contains sufficient memory to hold the decrypt ?
Question 2)
Given a binary tree which contains values at each node , find whether the path exist from root to the "LEAF NODE" such that sum of the values of d path nodes is equal to the GIVEN SUM. if so return true or else return false
Question 1)
Eg:
Input linked list:
1->2->3->4->a->b->c->d->5->6->e->f
Output should be in below format :
1->a->2->b->3->c->4->d->5->e->6->f
What is your favorite software product and how would you improve it?
Imagine a bit map representation of a television screen.write code to Go to a position (x,y) on the screen and flip the bit i.e. 0 to 1 or 1 to 0? He told me that I should ask a question as to what is the length of the screen or height of the screen to implement it which i didn't.
I applied for a Technology analyst position in nomura securities. It was completely behavioral. They went through my resume and asked questions based on my college projects? Why nomura? why not some technical company? why did you want to work for a financial firm in comparison to some technical company? Waiting for my result. Fingers crossed.
This was onsite.
Code review, gave some c++ code and asked me to find memory leaks. Its easy if you just go to the methods and pass some inputs. write code for atoi(return the integer part of the input i.e.if 1234abcd is input then u return 1234. Design a Game....I choose poker.write all the classes and methods you may use in them. They also asked me a question based on the implementation of Trie. I got reject because i didn't do well.
Differences between C and Java?How is memory managed in Java and C? what is your favorite algorithm?Write code to insert an element into a binary search tree?
What is hash map? How do you insert an element into it? what happens when i insert another value for the same key and I do get for that key? What is queue? what is priority queue? should priority be integral? can they be string comparisons as priority?
Write a program for prime numbers? improve the number of divisions that you are performing from all the numbers from 1 to that number to some less numbers. improve by seeing if you can decrease the loop from n to some lesser number.
Design a deck of cards that you may use for poker? what are the classes and methods that you use.
Imagine two linked lists and return the first similar element of the first linked list found in the second one. So when you join those two linked lists then it would form an alphabet Y and you are returning the common point. what would be the time complexity?
Given a tree, parse the tree using breadth first search and then find the last element in the tree. After finding the last element, replace that element with the root node. Eg. Input:
A
B C
D E F GOutput:
G
B C
D E F AGiven a binary search tree. Find the maximum depth of the binary search tree iteratively.
You are given a tree where child nodes point to parent (there is no link from parent to child). Give any two nodes in the tree, write a function to find the lowest common ancestor.
Node* LCA(Node *p, Node *q){
}
You are given a very large array of numbers (positive integers) in any order. Print the numbers that are duplicated:
1. No memory constraint
2. Limited Memory
Design a data structure where the following 3 functions are optimised:
1. Insert(n)
2. GetRandomElement()
3. Remove(n)
Write a class, and implement the functions. Give complexity of each of these ..
For example, give the letter (p,o) and length of 3, produce the following output(in any order you want, not just my example order)
ppp ppo poo pop opp opo oop ooo
another example would be given (a,b) and length 2
answer: ab aa bb ba
for each age value that appears in students table ,find the level value that appears most often
students(snum:int,sname:string,level:string,age:int);
Given constant integers x and t, write a function that takes no argument and returns true if the function has been called x number of times in last t secs.
How do you determine if a point is
1) inside a triangle
2) outside
3) on one of edge of triangle
4) if the point is one of the points of triangle
In a university, students can enroll in different courses. A student may enroll for more than one course. Both students and courses can be identified by IDs given to them. Design a data structure to store students, courses, and the student-course relationships. You can use arrays, lists, stacks, trees, graphs, etc. or come up with your own data structures. Give the running times, in Big O notation, for the following operations for your data structure and justify the answers: a) Return all students in a list. b) Return all courses in a list. c) Return all courses in a list for a given student. d) Return all students in a list for a given course.
]A shop sells an item in packets of 6, 9, and 17. A customer can buy any number of packets, but a packet cannot be broken up. Provide an efficient algorithm to solve the question "Can I buy N items?". For example, is it possible to buy 29 items? What about 19? Your algorithm simply needs to return true or false.
Write a function which traverse the whole tree and return the linked list of nodes.Your code should also be generic enough to work on any tree exp Binary tree, General tree etc.
How do you find the value of PI without using a circle? Sorry, should have given more details, basically "How does a caveman find the value of PI?" Assume he knows basic mathematics
What kind of benefits are you looking for?
What kind of working environment do you prefer to work in?
Are there any specialized areas you would want to work for?
Salary expectations?
Working of Cache (Include Temporal and Spatial locality || also Write through and write back mechanisms || Set-Associativity etc.)
Compiler optimization for memory based code. How do you make sure your code works fine with such a code?
Three men on their way from San Jose to New jersey by walk, decides to rest under a tree, And all go deep sleep under it. A fourth person who was passing by the tree, wanted to have fun and draws a smiley face on the forehead of all three and leaves. After all three wake up and they start smiling at each other checking out smiley faces on each other. But only one smart one realizes it. How does he realize it??
You have an coin as information source which outputs a sequence of Heads and Tail string as "HHHHTTHTHTHT...". And this data is supposed to be communicated over a channel using the function bool send(char *); optimize the solution for maximum throughput.
Write an O(n) based algorithm to find the nth node from the end of a linked list. You may want to check the boundary conditions too while working on it.
Two microprocessors communicating via UART channel. One microprocessor connected to a VGA based monitor output and another mircroprocessor connected to keyboard.
Sreen--uP1<--uP2---Keyboard
If you key in {A,B,C,D..} on keyboard, your monitor on other end displays {A,A,A,..}
Think in about debugging process and possible errors.
Design a mask for the string M, which has to replace the bits of N at i th position. Given a the bit-length of sequence N as j. Design a function to return the masked data.
Calculate limits of memory buffer for a transmitter station. Channel capacity is 1Gbps.
Design the packet size and the communication protocol. Given the turnaround time as 1ms.(Tx-Rx: 500usec and Rx-Tx 500usec). Optimize for minimal memory requirements.
Find numbers in an array that sum to a certain number....Once number is found return the index of both the numbers...We are not allowed to use Hashmap or any other DS...we have to do it inplace...using the same array
- Scrollable is an interface
- Writable is an interface
- TextScreen is an abstract class
- Videoscreen is a class that extends TextScreen and implements both Scrollable and Writable
in the scenario above which of the following statements is always true
a. A VideoScreen object cannot be passed to a method that expects a Writable
b. A Scrollable object can be cast to produce a VideoScreen
c. A VideoScreen object cannot be passed to a method that expects a TextScreen
d. VideoScreen can be cast as a Scrollable
e. A VideoScreen cannot be passed to a method that expects a Scrollable
Suppose we have an array like
1,2,3,4,5,a,b,c,d,e where we have always even number of elements.First half of the elements
are integers and second half are alphabets we have to change it to like
1,a,2,b,3,c,4,d,5,e in place i.e no use of any extra space, variables are allowed ..
Suppose there is a circle. You have five points on that circle. Each
point corresponds to a petrol pump. You are given two sets of data.
1. The amount of petrol that petrol pump will give.
2. Distance from that petrol pump tp the next petrol pump.
(Assume for 1 lit Petrol the truck will go 1 km)
Now calculate the first point from where a truck will be able to
complete the circle.
(The truck will stop at each petrol pump and it has infinite
capacity).
Give o(n) solution. You may use o(n) extra space.
Given a matrix you have to find the shortest path from one point to another within the matrix. The cost of path is all the matrix entries on the way. You can move in any direction (up, down, left, right, diagonally)
e.g.
5 9 10 1
3 7 4 4
8 2 1 9
So shortes path from (0,0) to (2,2) is (0,0)--(1,1)---(2,2). Path cost - 5+7+1 = 13
Write a function that returns true if it not returned n trues in last k seconds in O(1) time.
Design maze data structure and find path between 2 cells with modularity and extensibility.
A white cell has been given. Every second, the white cell gets divided into 9 parts in which middle one is black and all other remains as white. Black cell (if any) also gets divided into 9 cells which are all black. Given time passed, x(horizontal) and y(vertical) indices of the cell, find the color of the cell. Ex: timepaased as 1 and x,y(index starts from 0) as 2,2, color is white. For timepassed as 2, x,y as 4,1, color is black.
You are given a tree (an undirected acyclic connected graph) with N nodes, and edges numbered 1, 2,
3...N-1. Each edge has an integer value assigned to it, representing its length.
We will ask you to perfrom some instructions of the following form:
DIST a b : ask for the distance between node a and node b
or
KTH a b k : ask for the k-th node on the path from node a to node b.
Where does the definition of printf() lie ?
Given an arry Arr[N] of integers and a function int func(int x) that takes an integer and returns either 0 or 1 (depending on some property of the integer). Give the most efficient algorithm to store the numbers in the array in such a way that all numbers that return 1 should come before all numbers that return 0, when called upon by the function func
given a village with demons and a sleeping man, The man is always sleeping ,never wakes up. Now a demon can eat the sleeping man , but after that
he will fall asleep , any demon can eat another sleeping demon.
If demons are very smart and would always choose to stay alive than to eat the man and risk their lives.
so if initially there are 65 demons and 1 sleeping man ,, what would happen in the village ???
Given a sorted array of Infinite size, find an element ‘K’ in the array without using extra memory in O (lgn) time. (Remember the array size is infinite that is no upper bound
If I give you a binary number, get me the nearest multiple of 8 which is greater than the number. Use bit manipulations.
Reverse a stack without using Extra memory (we can use recursion).
A person can climb stairs in 3 ways: Either a single stair at a time or 2 steps together or 3 steps at a time. So, if you have total N stairs give a recurrence relation to solve the above proble
code to find mth maximum element in an array...size of array (n) is greater than m
For the given number need to find out the possible BST. eg, if the given number is n means we should find BSTs using 1,2..n. n=5 means figure it out using 1,2,3,4,5, how many BST we can make?
Write a program that performs division and outputs quotient. You cannot use division operator.
I thought I could do it with mod but I was wrong. He, told that the solution will not work. After keeping the phone down I realized that subtracting the divisor from the dividend and continue this in a loop till dividend >= divisor would be the right way to go (along with other validations like check for 0.)
In a 3d space find points 10 points that are closest to the origin. Which data structure would you implement. What would be the time complexity of such a program.
I said that I would maintain 10 arrays that stores (x,y,z) coordinates and 10 int var to store the distance value.
int coordinates1[],value1,coordinates2[],value2,coordinates3[],value3....
We would start calculating Euclidean distance of the given point in hand and store it in those 10 arrays. As soon as we got 11th point we would replace it with the array corresponding to the highest value in the array.
As soon as we got the 12th point we would replace it with the 2nd highest corresponding value array ...after traversing through every point we would have the nearest 10 coordinates. I read this somewhere on career cup. I just modified the idea a little to accommodate 3d realm.
He asked what is space complexity. I said 10 arrays and 10 int values. A constant number will have a constant value n, O(n). He said fine, what if there are k points to be found. I said still it would be O(n). He said I was wrong it would be O(n square) since k points are inputted. I did not understand that part.
If have allocated an array of integers using new operator. How can the memory be freed using free(not delete) ?
If have allocated an array of integers using malloc(not new). How can the memory be freed using delete(not free) ?
Algorithm to find the square root of a given number in C without using sqrt
Given an Array A={-2,4,30,-50,90,-60,100,120}
The array index represents time of day.
Say 0-9 A.M, 1- 10 A.M....etc
And value represents stock price at that time.
Get the max profit. i.e in this input,
best buying price=-60
best selling price=120
Explain STL maps- Hash tables and buckets.
Given a BST find the kth largest element in the BST with single traversal and without using any extra space.
Simple questions were asked.
1. Get the number of employees from every department given employee and dept tables.
2. How would you optimize a query considering that it is performing very bad.
3. What happens behind the scene when you hit any website URL in the web browser.
Visualize holding an N-ary tree by its root in your left hand. Now hold any node in the tree with your right hand and release the left hand. How the tree would transform and give an algorithm to do it programatically.
Given an array such that ever number differ from its adjacent number by at max 1. Find a number in this array efficiently.
I told him i knew this question already and explained the answer real quick.
Vertical summation of a binary tree.
I told him I knew this question already and explained the answer real quick.
given a number say 312. find the next number using the same digits. 321.
How would you do check valid parenthesis in less than O(n) time. He was looking for divide and conquer.
We had a debate about it being in O(n) and he asked me to think about it in threaded environment.
Write a function to check valid parenthesis.
(()) - valid
)( - invalid.
Give a design for chessboard which allows two people to play. (Class/Object level)
Explain about a project I had in my resume from previous company in detail. (really detailed) :)
Give a low level (class/object) design for the document write component in the amazon's websync.
Give a high level design for amazon's websync architecture.
Given a huge file with number and limited memory, how would you sort it efficiently.
He was looking for external sort as the answer.
Given an array like below, construct a N-ary tree from it.
322100100
each number represents the number of children starting with root.
3
/ | \
2 1 0
/ \ \
2 0 0
/ \
1 0Write a function to check if a binary tree is a binary search tree.
How much memory will be allocated from the "stack" for the following declarations together?
int *a;
char *b;
This was an objective question. a and b have not been malloced yet.
int a = 323235,b = 133423,c;
int *p = &a,*q = &b;
c = p - q;
for the snippet above, the value of c is 1. Why is it not the difference of the address values in p and q ?(i.e 4)
you have an array of integers, find the longest
subarray which consists of numbers that can be arranged in a sequence, e.g.:
a = {4,5,1,5,7,4,3,6,3,1,9}
max subarray = {5,7,4,3,6}
Implement barrier synchronization using semaphores.
That is, suppose you have n threads which should wait on a barrier until all of them arrive.
A new USB memory device is designed with the following functionalities.
1. when connected to a camera, it opens the data transfer wizard.
2. When connected to another storage device, it copies data.
3. When connected to a smart phone, it sync's. the contacts
<there were a couple of others too.>
Write the test cases.
write a function to reverse a linked list in the following fashion.
given: a list : a b c d e f
a number N
output should be: if N=2
b a d c f e
if N=3
c b a f e d
ie, the list should be reversed in <N><N>...<N> intervals. We are not allowed to allocate any new nodes.
find the number of solutions (non-negative integral) for the equation x1+x2+x3+x4+x5=20.
ie, #((0,0,0,0,20),(0,0,0,20,0),....)
Given a Binary tree and a pointer to some node in the tree, find the left and right neighbors of the input node. The neighbor nodes are on the same level/depth as of input node.
Don't use BFS/level order traversal.
There is no parent pointer.
{There are lakhs of co-orddinate Points P(x,y) as input data. A library function int findDistance(x,y) has been provided to you which will give the distance of P(x,y) from origin. Find 100 points which are at least distance from origin.}
{You are given an unsorted array of integers. You have to find out the first sub array whose elements when added sum up to zero.
eg:- int Array[] = {1,2,-4,-3, 6 ,3.....}Here sub array is -3,6,3 bcos adding all these sum to zero. A sub array can be of size 2 to whole length of the array. You can use extra space also for the same
find the index of the highest bit set of a 32-bit number (without loops obviously)
Given a binary Search tree and a Node, How would you transform the tree to make that Node as root.The resulting tree should be a BST.
Given two version numbers as string (can be very long) write a function which returns 1 if first one is latest, -1 if second one is latest and 0 if they are equal.
Ex: 1.2.0.4.5
1.2.1
We have write our split method with period as delimeter and we have to handle all the malformed version numbers like 1..2.0 etc and similar other exceptions
a) You have a package repository in which there are dependencies between packages for building like package A has to be built before package B. If you are given dependencies between the packages and package name x, we have find the build order for x.
Ex: A → {B,C}
B → {E}
C → {D,E,F}
D → {}
F → {}
G → {C}
For package A, build order is E B F D C A (may not unique)
Given a function Set<Package> getDependencies (Package packageName) which returns a set of dependencies for a given package name, write a method List<Package> getBuildOrder(Package packageName) which returns the build order
b) How would you handle cyclic dependencies (Algo only)
Given an array of stock prices from day 0 to N-1 of a company X, we have to find the max loss that is possible. Loss occurs if stock is bought at higher price and sold at lower price.
Ex: 1 2 3 7 5 8 9 4 6 10 12 (algo and code including main)
Max Loss is 9 - 4 = 5 (Possible losses are 8-4 = 4, 7-5 = 2 etc). Max difference between stock price is 12 - 1 = 11 but max loss is 9 -4 = 5
Find the angle between hours hand and minutes hand.
Given a string, we have to find all the unique words present in the string. Assume that words are delimited by space character and we have to write our own split function. We have to handle all the edge cases
You are given an infinitely long array of integers in which some part of the array is sorted and all other entries contain terminating character ($). Given a number how will you search in the given array. What is the complexity of the search operation if the number is not present in the array
Ex: 1 2 3 4 5 6 7 8 9 $ $ $ $ $ $ $ $ $ $ $ ….........................
You are given two strings, delete the letters of second string from first string and print the resultant string
Ex: Input: Hello, Hai Output: ello
Reverse the words in a string
Ex: Input: “This is Java” Output: Java is This
Two numbers are given in the form of linked list with most significant number as the head, we have to add them and return the resulting number as a linked list again.
Ex: Input: 1-->2-->3 4-->5 Output: 1-->6-->8
Given a binary tree and a node in the binary tree, find the next node in inorder traversal
Find the min depth from root to leaf in binary tree
Ex: 1
2 3
4 5
Output: 1 (since leaf 3 is closest to root)
A binary tree is given we need to print vertical sums of nodes. for example
1 2 3 4 5
| | 5 | |
| | / | \ | |
| | / | 8 |
| | / | / | \|
| 4 | / | 10
| / | \ 9 | |
| / | \ | |
7 | 6 |
| | | | |
| | | | |
-----------------------------------------------
7 4 20 8 10Here we need to print sum 7,4,20,8,10.
There is sorted integer metrics(5,5). Write the program which through we can find the any integer value on this metrics.Search(int searchItem,M(5,5).
Convert the integer in to string representation of the int value. Example : Like 41 = Forty one, 441 = Fore hundred Forty One , 3441 = Three thousand Fore hundred Forty One....
assume you have a program which constantly crashes at some place. Yet, if you insert a 'printf' statement at this place, it magically begins to work.
What does this indicate ? How can you trace the problem ?
Data structure used in parking lot.
Design a parking lot where cars and motorcycles can be parked.
how exactly virtual table and virtual pointer functions.
write a program to reverse a linked list.
create 4 equilateral triangle using 6 match sticks.
Convert a binary search tree to a sorted doubly linked list in O(n) time and in place. Manipulate the existing tree. Donot create a new tree.
Find the maximum continuous sum in an array. The array will contain at least one positive integer. Report the actual sequence. If there are multiple sequences report any one.
Sort a link list using merge sort.
Design and implement a garbage collector in c++.
Brief abour AVL tree
remove duplicates in an array.
given a value 'N', generate all possible valid combinations of parentheses.
example: N=2
valid parentheses: ()(), (())
check if two strings are anagrams or not
Given a 2D array which has elements sorted both row-wise and column wise, find an efficient way to search a given key.
Ex: a1 a2 a3 a4
b1 b2 b3 b4
c1 c2 c3 c4
a1<a2<a3<a4 (for all rows)
a1<b1<c1 (for all columns)
Find the Number of Verticals in a given Binary Tree.
Example: a
/ \
b c (no. of verticals = 3)
a
/ \
b c
\
d (no of verticals= 3)
Input : 4 jars and 50 balls of different colors (Red, Green, Yellow, Blue) where each jar can contain a maximum of 100 balls.
Problem : When a user draws a red ball he looses his money while if he draws a ball of some other color his money is doubled. Arrange the balls in such a way that the user has highest probability to loose.
Given a Binary tree and a pointer to some node in the tree, find the left and right neighbors of the input node. The neighbor nodes are on the same level/depth as of input node.
Don't use BFS/level order traversal.
There is no parent pointer.
Given a linked list with each node having two pointers: A next pointer pointing to the next node and a random pointer pointing to a random node in the link list. The random pointer can also point to null.
Struct Node
{
int val;
Struct Node* next;
Struct Node* random;
}
Write a function Node* CloneList(Node* head) to clone the list.
We have a link list with given head looping back to some node.we've to find the node at which it's looping back with least complexity.
a->b->c->d->b
Convert an array "a1 a2 a3...an b1 b2 b3...bn c1 c2 c3...cn" to "a1b1c1 a2b2c2...anbncn", inplace.
Main Question:
Design a parallel Breadth First Search algorithm for a directed weighted graph.
Basically you need to find the minimum cost to reach to a node from the starting node <given>. (Just save the optimum cost and not the optimum path). Calculate and output the optimum reachability cost for all the nodes from a given starting point.
Implement in C with openMP.
1. How about using DFS or Shortest path first instead. Would these algorithms perform better than BFS with parallel implementation. Yes/No Why?
There 2 bucket of 3L & 5L. How to measure 4L?
there are unlimited ropes of same length and if we burn them it will take 1 hour.
How to measure 45 mins?
There are four people at the end of bridge. They take following time to cross the bridge:
1st: 1 min
2nd: 2 min
3rd: 7 min
4th: 9 min
Condition:
1. They have only one torch and they can't cross bridge without torch.
2. and only 2 person can cross bridge at a time.
Write a program to copy the string?
Write a algo to check tree is balanced?
Write a algo to find the Height of the Tree?
Give algorithm for a natural sort, i.e.
if we are given following 2 string -
A11B
A5B
then the result should be
A5B
A11B
as 1st letter is same but at the second place 5 <11 and
Two numbers A and B are given. Both can be -ve or +ve. find no of 1's in 2's compliment representation between A and B.
Find if a binary tree is bst
Find if a given string can be used to construct a palindrome. O(n) time and O(1) space.
Ex: A1R.A1R - contains a palindrome.
BCDDDCG - doesnt contain palindrome.
Also, try to keep the solution less than 2n operations.
reconstruct a BST given its preorder traversal only...u cant use extra space and do it in O(n)
This question has been repeatedly asked many times
Suppose you are passing a string to a Formatter function. Get the formatted news feed output string such that* There should be one sentence per line.* There shouldn't be any spaces i.e. the line shouldn't be blank.
Find if the given string is palindrome. Eg. palindrome string "..AB ,, CD, ED. CB...A...". No extra buffer available.
You are given a binary tree that has many binary search trees as subtrees. Find the largest (in terms of nodes) binary search tree (subtree). You are given the root node to binary tree. (Binary tree is different from binary search tree).
Minimum/Maximum Sum path in A Binary Tree
Find and Print the Root to leaf path with minimum sum.
Finding such a path is easy bt how to print only that path..
u can not modify structure of tree node..it has a data with left and right child pointers.
Use as minimum space as possible
Assume you have a file with 5Mb size.
Each line in file has a interger. (and only one integer per line).
Now, your system can process only 1Mb data at a time in memory, that is you cannot access more than 1Mb of data at a time.
Write a program that sort the file under this circumstances.
Answer I gave:
This problem is basically, you have array of 100 number, and at time you can access only 10 of them. Then sort the array.
He was happy to see this analogy, and then my algo.
Divide the array into 10 segments of each, and sort each one of them individually.
Now, take the first element of each sort subarray and find the min.
Put this min into differnt array of the size 100 at its starting location.
Repeat this process, for the next element from the subarray which had the smallest element as identified earlier.
He seemed to be ok with this.
Any other approach?
Given a string S of words and no of character per line m ,with m being greater than the longest word in S,print S in a set of lines so that each line contains no more than m characters and no word split between 2 lines.
Write a program which gives a numerator and a denominator, prints the fractional value in a special format. eg. Numerator: 1, Denominator: 3. So Num/Denom = 0.3333333333, but output should be .(3) similarly 0.123123 as .(123) also 0.34232323 as 0.34(23)
If there is a n-digit, print the digits one by one without using temporary storage and how will you do it efficiently?
Example:
if the number is 1054
print:
1
0
5
4
give ur introduction why samsung what quality u lack and what u r doing to improve it.
how compiler generates unique names for overloaded functions, if two functions have same name and same parameters but differnt return type , can it be possible i said no he asked why . i explained about the name mangling and showed that return type does not play any role in name mangling.
tell me about about function pointer , how to call a function using function pointer.
which is faster c or c++.
what are call back functions.Why they are useful.
if polymorphism is possible in C if yes then how.
how to correctly instantiate this class:
template < template < template < class > class, class > class Param >
struct Bogus {
int foo() {
printf("ok\n");;
}
};what is Vtable explain and give example. design a class and make virtual table for that.
Given an int array which might contain duplicates, find the largest subset of it which form a sequence.
Eg. {1,6,10,4,7,9,5}
then ans is 4,5,6,7
Sorting is an obvious solution. Can this be done in O(n) time
Given an int array which might contain duplicates, find if it is a sequence.
Eg. {45,50,47,46,49,48}
is a sequence 45, 46,47,48,49,50
Sorting is an obvious solution. Can this be done in O(n) time and O(1) space
Partition an int array in 2 equal parts such that the avg of two is equal.
Provide algo only, dont write code
How can you merge two BST inplace so that preserving the BST property?
Provide algo only, dont write code
#include<stdio.h>
int main() {
int i,j;
j = 10;
i = 3;
//i = j++ - j++;
//i = i++ + ++i;
//i = j++ - j++ + i++ + ++i;
printf("%d\n", i);
}If I un-comment the first comment then output = 0
if second then output = 9
if third then output = 8
Please explain why this is so
How we can update the GUI using the background thread?
main() {
int i,j;
j = 10;
i = j++ - j++;
printf("%d %d", i,j);
}The output of this is 0, 12
can anyone please explain me the logic
How to solve DLL circular dependency?
e.g.:
DLL-A depend on DLL-B
DLL-B depend on DLL-C
DLL-C depend on DLL-A.
What are delegate and how it work internally?
delegate is a type safe pointer in C#. But using pointer is restricted in C#? So how it is implemented?
How Garbage Collector work and who trigger GC calling?
How GC work in-side of a process and between mutithreads?
We have a file containing all product IDs. Write a code to retrieve all the Unique IDs that start with 'b' and doesn't have any special characters in it.
Write test cases that could fail your code.
What kind a data structure will you use to implement an Instant Search feature
double payment = 0.1;
double sum = 0.0;
for (int i=0; i<10; i++)
{
sum += payment;
}
why is output 0.9999999999999999
public class TestFloatingPoint {
public static void main(String[] args) {
double payment = 0.125;
double sum = 0.0;
for (int i=0; i<8; i++) {
sum += payment;
}
System.out.println(sum);
}
}
Why does this give 1.0
main()
{
char *c;
printf("\n%d", *c);
printf("\n%d", c);
printf("\n%d", &c);
}output of above program.
*c some junk value, c some memory address, &c address where the pointer is stored.
Q. if we re-run the program, then what's the output.
A. all output may change.
He stressed that &c won't change, everything else might..but &c will remain same.??
I just tried on my unix box, and saw it to change?
This is incremental.
Q1. Write the the algo for linked list traversal.
Q2. Now, modify this to give the index of a element "x" in list (index== its location in list, rather number of comparison needed to finally get to X, else 0)
Q3. modify and give the prototype of function will work generally (that means a function prototype which takes any data strcutre(list, q, tree, heap), X, and return the count)
Q4. Now declare the function defined above.
Answers I gave:
1.
bool traverse ( list * head) {
while (head) {head=head->next;}
return TRUE;
}2. bool findx (list *head, void *x, int num_bytes)
{
bool ret = FALSE;
while (head) {
if (memcmp(head->data, x, num_bytes)){ ret=TRUE; return ret;}
else ret;
}
3. int findX(void *head, int (*traverse(void *node, void *x))
where *traverse is a function pointer that can be changed depending upon data structure for which we need to find the index of X.
Given two of integer arrays, find the intersection.
Compose a new sorted array from two already sorted array.
you have a infinite set of coordinates and you have to find out the 100 points closest to the origin.
Reverse a doubly linked list.
What happens behind the scene when we typ an url in browser and hit enter?
A question on set of pair of processes and scheduling them.
Topological sorting in graphs.
Explain data structure and design for list feature or auto complete suggestion.
Tries and Has map implementation.
Given a singly linked list with a loop. Find exact location (the element number) where the loop starts. Obviously, using O(1) space (this also means you are not allowed to associate any data with the list elements)
find out
missing no. from a stack if two given stacks have same numbers
2)next question is given an
array of integers...like 10 12 16 17 24 27 8 6 5 4 2....first from 10 to 27 it is in increasing order... .and then decreasing order
starts....so he asked me to find the position from where decreasing starts....it should be done in O(logn).
write a c code to print all d pattern of numbers generated by given number of 0's and 1's...say m 0s and n 1s
write a c code to reverse a string by word..
e.g i/p = he is a geek
o/p should be = geek a is he
Given a binary tree and a no X.find if there exist a path that sums to X.
Note:path may or may not start from root.
given a 32-bit integer x
find the smallest integer x0 > x
with the same number of ones in binary representation
Example:
x = 76
x0 = 81solution without loops and additional storage ?
Find the number of ways of placing 3 balls in 3 buckets. buckets are of diff capacity.
bucket1 can hold 2 balls
bucket2 - 3 balls
bucket3 - 2 balls.
ex. 1 1 1 is valid
0 3 0 is valid
Write a function of Toupper and ToLower in C#
u have to perform following tasks in O(1) time
1.)insertion
2.)deletion
3.)searching
no range of input numbers is given
wat data structure will you use?
if u use hashing wat will be the key and value pairs??
Find out the middle node in the given singly linked list in one traversal.Length will always be an odd number.
soln1: Two pointer approach
soln2: Usual method of finding length in one traversal & then finding the middle node in the second traversal.
Question: which method is better & why ? As far as i know both the method needs two traversal though they do it different time.(i.e) either after finishing the first traversal or while the first traversal is going on.? and if u notice carefully the same amount of work is done in both the methods...now tell me why the two pointer approach is preferred??.
1h 15m.
given a polynomial f(x) of degree n, i.e.:
f(x) = f[n]*x^n + f[n-1]*x^[n-1] + ... + f[0]
propose an efficient algorithm to computing
the coefficients of g(x) = f(x+1), assume arithemtic overflow cannot occur.
Example: f(x) = 5*x^2 + 3*x - 1
g(x) = f(x+1) = 5*x^2 + 13*x + 7Is context switch a O(1) process or the context switch quantum is dependent on various local factors that can affect the time taken for it.
I responded, saying its a O(1), provided we treat each operation as process swap-in/out as single atomic events.
give a binary tree (not BST)where tree node, with extra pointer inorder-successor, initaliy all inorder-successor pointer set to NULL.
write a code to set all pointer to its inordersuccessor.
struct Node
{
int data;
Node *left, *right;
Node *successor;
};
Assume that there are n numbers (some possibly negative) on a circle, and
we wish to find the maximum contiguous sum along an arc of the circle. Give an
efficient algorithm for solving this problem.
check whether two strings are rotational equivalent of each other.but u cat not use any linear string matching algorithm like rabin-karp,parse tree etc.still do it in o(n).
How will u check whether a given tree is symmetric with structure wise not with the data.....
ex:
Symmetric structure wise
5
/ \
3 9
\ /
4 8Not symmetric
5
/ \
5 9
/ /
3 8Implement Smart Pointer?
This question regarding RTTI in C++..
How dynamic_cast work internally...
a linked list contains
2 19 _ _ 3 47 _ _ _ 2 20 _ _ ..............and so on
I have to fill those empty nodes with numbers whose sum is equal to the numbers
occurring just before the gaps and the number of gaps is determined by the node
which is at 2 distance before the gaps with the limitation that there would be no
repetition in list only the nodes designating the number of gaps can be repeated
for example 2 20 should be broken in two parts like 19 1
3 47 should be broken in three parts like 42 2 3
and not in 44 1 2 because 1 already occurred in the list due previous partition
how to detect/remove duplicate entries frm a database(for eg students). thr is no primary key
Given an array of integers (can be both +ve or -ve), find the three integers which multiply to give the largest product.
My solution: Sort the array, separate out the negative part and the positive part.
prod1 = product of 3 largest +ve integers
prod2 = product of 2 smallest -ve integers with the largest +ve integer
Compare prod1 with prod2, whichever is larger, that is the solution.
Obviously taking care of boundary cases. Any ideas?
Given an array of size N consisting 3 distinct numbers, how would you sort them using swapping in O(n)?
My answer: I initially came up with "Counting Sort", then came up with a linked list based solution. But he told me I could come up with a swapping based solution in O(n). Any ideas?
There are 3 products table,chair and bench. Product can be of wood ,metal and plastic . Design a class structures for this.
Given a list
emp1 manger1
emp2 manager2
It contains all the employes and manager relationship. From this list construct the organizational tree of company. Write programme for it.
Given a array,find out if there exist a subarray such its sum is zero.
How do you partition an array into 2 parts such that the two parts have equal average?...each partition may contain elements that are non-contiguous in the array....
in linked list how to find the 1/3rd and 2/3rd nodes efficiently...
ex : 1-->2-->3-->4-->5-->6.
outout :
1/3rd - 2
2/3rd - 4
Question on c++ templates...
template <class T>
T max(T a, T b)
{
return ( a > b )? a : b;
}
for built in data types it will work fine .. if we send class objects as parameters then how it will work??
class ex
{
int i;
public:
ex(int ii = 0):i(ii){}
~ex(){cout<<"dest"<<endl;}
void show()
{
cout<<"show fun called"<<endl;
}
};
int main(int argc , char *argv[])
{
ex *ob = NULL;
ob->show();
return 0;
}
what happens when we call show method.
How to replace the space in the string with "ABC" without using extra memory.. string may contain some extra memory.
str = "i am chandu" -- str contation more memory...
str = "iABCamABCchandu"
how to implement stack using BST??
Write a program to reverse a character array "Hello World". Give different test cases(input arrays) to test your code.
Write a program to find the smallest number from an array with elements{1,10, -5, 10} Write the test cases for it(Give different input arrays to test ur code)
Design an algorithm to perform operation on an array
Add(i,y)-> add value y to i position
sum(i) -> sum of first i numbers
we can use additional array O(n) and worst case performance should be O(log n) for both operation
Write a program / Aggorithm to solve generalized M liter and N liter Jug problem which will tell to the user whether K liter is possible or not from the M and N .
For Example :-
M=3 and N=4 and K=5 . Its possible to produce 5 liter with the help of 3 and 4 liter . He wanted to have a running algo/code for the same .
How to find the outside temperature when you are in a room ? There is no thermometer or TV or any other person or sensor which can tell you anything.Although there is a window in a room.
after the memory allocated then we can removed elements from any where in the list
what is better to use single linked list or double linked list
why we used linked list, what's demand of linked list in the market
There is a large document. which contains millions of words. so how you will calculate a each word occurrence count in an optimal way?
I aksed in the end: Why Amazon?
Give an Integer Array N[], and an Integer X.
Find the number from N[] that for each elements which they are added up to X.
Its just like white board coding test, but you need to write your own exception handler and also write enough tests for it.
Good luck!
Tell me about yourself?
You are given 100 stations and distance between each adjacent stations. Now you have to select 10 stations(means 10 hops) among those 100 stations in such a way that maximum of distance between any 2 hops will be minimised. By default 1 and 100 stations are selected , so you need to choose only 8 more stations.
The solution to this problem seems like Dynamic programming.
You have given a positive number you have to find a number which is bigger than that by using same digits available in the number .
Example :-
You have given a number 7585 , your output should be 7855 .
An array having 100 elements have numbers from 1 to 99 randomly out of which any one number is repeated. I was asked to find repeated number in min time nd space complexity.
You are given a string sequence and program need to output the number of times consecutive character sequences happen for increasing sequence length. eg. aabbababbd has 2 sequences as a followed by a, b followed by b. The for sequence length 2, ab followed by ab at 5th position. This is to be coded in minimum complexity.
Given an array of strings of 0s and 1s. X and Y are also given. Return the maximum number of elements in a subset of the array elements which will X number of zeroes and Y number of 1s when combined. For eg: if array[] = {"01", "10", "0", "110"} X=3, Y=2
Answer should be 3 since first 3 strings when combined will give the required number of 0s and 1s.
Print the numbers of form 2^i.5^j in increasing order. For eg:
1, 2, 4, 5, 8, 10, 16, 20
Give an algorithm for finding the shortest distance between two words in a document.
First I proposed O(n) solution read the whole document and update min distance according to the position found.
Then he said if there are millions of words and we are querying multiple time then what will be the case.
Then I gave hash table solution. For each words maintain list of positions in hashtable and then for each position in word1 list do binary search in word2 list. But if there are only two words in the document then this solution will fail. time complexity will reach O(n^2).
any better solution?
hey..can any1 plz tell me diff btw super key,candidate key,composite key....was asked in in interview..i was confused...also need an explanation for super key
You have got two jobs J1 and J2. You have two threads T1 and T2 for the respective jobs. Write a program such that you can assure that J2 will start only when J1 ends
How many types of class loaders do you know in java
What is request forwarding and request redirect
You have two hashmaps HM1 and HM2 where key = Id(long) value = timestamp. You need to give a program to return a list of Ids combined from both the hashmaps such that they are sorted as per their timestamps
How will you make your own Hashmap class?
Given an array arr[] of n integers, construct a Product Array prod[] (of same size) such that prod[i] is equal to the product of all the elements of arr[] except arr[i]. Solve it without division operator and in O(n).
given a expresion
2*3+5-3 it consisitof 3 opertors(+,-,*),but they can occur more than time.
we have to maximise the vlaue of expression by adding parathesis
like 2*3+5-3=8 no paranthesis
2*(3+5)-3=13
2*(3+5-3)=10
and so on maximise it with differnt possible parathesis
given the following inheritance scheme
class A
{
}
class B : public A
{
}
class C : public A
{
}
class D : public C
{
}
Given a function
static void foo(C * obj)
{
}
which one of the above defined classes' pointer can be passed into the function foo()
What is disadvantage of polymorphism ?
How virtual table helps polymorphism ?
Why destructor can't be overloaded ? (the answer is not the absence arguments to the function)
How to specify a timeout for a child process ?
(there is a child process. this is taking too long to complete the task. We need to kill that child process. )
Design a system to specify timeout for different child processes ?
How to detect deadlock in threads ?
How to prevent deadlock in threads ?
What is loop in linked list ?
How to detect a loop in a linked list ?
You need to implement a versioned stack, i.e. version of stack will increment after each push/pop. Apart from push/pop, implement a method print(n) which would print stack state corresponding to version 'n'. For example:
-> initially stack is empty.
-> Version 1: 11 is pushed
-> Version 2: 8 is pushed
-> version 3: pop. only 11 left
-> Version 4: 15 is pushed
....
And so on.
Print(n) should print state at version 'n'.
Here 1 should print 11, 2 should print 8, 11...
All methods should be as efficient as possible.
Q2:Implement T9 moblie phone dictionary .But the problem was just to find all the posible outputs given the the sequence of key pressed.
My Solution :Recursion
private static String[] mapping = { "ABC", "DEF", "GHI", "JKL", "MNO",
"PQR", "STU", "VW", "XY", "Z*#" };
public static void combinations(int[] number, char[] buf, int numIndex) {
for (int i = 0; i < mapping[number[numIndex]].length(); i++) {
buf[numIndex] = mapping[number[numIndex]].charAt(i);
if (numIndex < number.length - 1) {
combinations(number, buf, numIndex + 1);
} else
System.out.println(buf);
}
}
public static void main(String[] args) {
int num[] = { 0, 1};// { 4, 8, 5, 9, 0, 3, 1, 7,6,2 };
PhoneBook.combinations(num, new char[num.length], 0);
}
He was looking for Trie data structure :(
It is my first phone screening, it consists of two questions , first question was pretty simple
Q1:WAP to find the sum of contiguous subarray within a one-dimensional array of numbers which has the largest sum.
My Soluton :Kadane’s Algorithm:
int maxSubArraySum(int a[], int size)
{
int max_so_far = 0, max_ending_here = 0;
int i;
for(i = 0; i < size; i++)
{
max_ending_here = max_ending_here + a[i];
if(max_ending_here < 0)
max_ending_here = 0;
if(max_so_far < max_ending_here)
max_so_far = max_ending_here;
}
return max_so_far;
}
PreOrder traversal without recusion
You have given an array give a function which returns a boolean telling whether the numbers in the array are consecutive or not.
Given 0*1*, find index of first 1
Given a big unsorted list of 64-bit integers, find an element not in list
an interseting problem
for a fibonacci series
the recurrence relation is
t(n)=t(n-1)+t(n-2)+O(1)
on solving it gives upper bound of O(n^2)
but when draw tree for the recurcsion we see that it is growing exponentially giving a complexity of O(2^n).
so what is the complexity for fibonaacci series n^2 or 2^n
given a string write all the possible upper case and lower case strings of it. eg. given a string THE print tHE,ThE,THe,thE,The,tHe,the.....
give me the solution
Write code to retrieve max-valued element from a stack. Time complexity must be O(1).
One way to do so is by keeping another stack, containing max elements and updating it for every push and pop operation.
I am curious if there are any other, possibly more elegant ways to do the same.
two 32bit integers m,n are given.replace all the bits in m from i to j locations with all the bits in n from k to l locations....
eg.m=110000000000 n=10101010 i=3 j=5 k=5 l=7
o/p:110000101000
some one give me the solution
develop a solution for an elevator system in a building having 50 floors.. the main criteria is that the lift should be available all the time
replace all the spaces in a string with %20
test cases for mobile phone
given a set of integers [6,8,41,36,58,69]
is there any way with time complexity better than 2^n to find 1 subset whose sum is equal to a given sum.
for eg:sum 49 ans 8,41
sum 105 ans 6 ,41 58
given two arrays [5 6 2 8 1] or [4 7 9 2 4]...such arrays are given, you have to find
possible pairs where sum of numbers in both arrays of a pair is equal....eg
for the first case it will be [5 6] and [2 8 1]
write a program to implement this
Given an array a int[5], there are 3 nos which are same and 2 numbers which are same. Write a function which should return true or false if the array is this way.
for eg . 4,4,4, 5,5
function should return true in the above case.
There is a drought situation in Agrabah.King got worried and called Aladdin for helping him out. As he is a modern Aladdin he took printouts of places around Agrabah from google maps.For analyzing the map properly, he converted the map into a M x N grid. Each point is represented by either ‘0’ or ‘1’.
‘1’ represents the unit area of water and ‘0’ represents the unit area of land. King told him to find the largest continuous patch of water so that he can send his people over there.
As our Aladdin is modern, but not a good programmer, he wants your help. Help him out by printing out the largest area water patch available on map.
How to find the max product of three numbers out of all elements of an array of integers.
Given a stack. Suggest a way to add a min() function which returns the min value among the all elements stack. The order of this function should be O(1) == constant and should not change order of other functions like push() pop() top()
Given there are integers in the stack.
Explain your college projects
Homework question (BUMMER) add two numbers in linkedlist using stack..I was not expecting this...this was surprise. I was packing my bags to visit my home country :))
Initially, we discussed, how can this problem will be solved...I suggested RECURSION, but he wanted to use stack, as it was simple.
I need to catch my flight at night..so was doing my homework in airport :) Code was working good, but I used standard stack and linkedlist libraries of Java. I forgot to ask interviewer, if he wanted me to implement those...
Explain how GC in java works
Design deck of card (Standard Amazon question)
Find lowest common ancestor of BST...code it in java
TCP vs UDP...is DNS a UDP or TCP
Puzzle, find car in infinite road..give complexity ( I took some time to get the solution, but made mistakes while giving complexities..but at the end with help of interviewer...could answer it)
Two number in unsorted order, find the sum(third number).
Explain the following:
left and right join...
outer and inner join
sql injection (???..could not answer..but he was ok, i think)
difference between equalto and == in java
How would you find out a word with maximum number of occurences in a big book ..like big big book..
Given a string. How to convert it into palindrome adding minimum number of character(insertion at any place) but no removal?
Given a matrix which represents 1/0 representing a direct flight between two places in a 2D array, find the number of hops required to reach from one place to another place. In other words, find if it is bi-hop, tri-hop etc.
There are two tumblers one 7 litre tumbler, one 4 litre tumber and ample water. Get 6 liters of water in 7 litre tumbler.
Given an array of elements and an integer x, rearrange the array such that all the elements greater than or equal to x should be in descending order and all the elements less than x should be in ascending order in most efficient manner.
Given two indices in a byte m and n such that m>=n extract all the bits between m and n in a single instruction.
Two very large numbers are represented using arrays. Multiply these two numbers. E.g. Two numbers 12 and 13 are represented as a=[1,2] adn b=[1,3]. The expected result is 12*13=156 i.e. c=[1,5,6]
Design a hashtable, you have 1000 items, how many slot would you choose. why.
You have been given a dictionary containing some words which data structure you will
use to store all those words and why
You have been given a word you have to find its anagrams within that dictionary
Now you haven’t been given any word you have to find all the anagrams already existing
within given dictionary.
Now you can have as much time as you want for preprocessing of dictionary words
already existing but the solution should give efficient result for accessing the anagram of
given word
Suppose the length of each word in dictionary is of length N and it has M no of words in
dictionary then how much time it will take for preprocessing and after preprocessing to
find the angrams in dictionary
(they were asking for as many solutions as you can give for each question)
You have a BST in which each and every node has an extra pointer (called rand) which
is pointing to any random node within the tree. Now if that rand pointer is pointing to any
of its inorder successor then its fine otherwise you have to make it null.
Now you are also having the duplicate entries in that BST. Now how will you handle it.
Next question was suppose the tree is not BST and also has duplicate entries what will
you do now to handle that rand pointer.
What is the time complexity and space complexity in every solution
design a data structure for a phone address book with 3 fields
name, phone number , address
one must be able to search this phone book on any of the 3 fields
how would you detect mouth in a picture
write iterative version of seed fill algorithm
find longest increasing subsequence not necessarily contiguous in nlogn time. I knew how do it n2 time but was unable to do it in nlogn
OO design for Vector Graphics Program.
Design a data structure for word processor
Find all permutations of a given string in lexicographical order.
Given a binary tree. Find the minimum element at a given depth.
Given an array which is sorted in ascending order upto kth element and then in descending order. Find the maximum element.
Find 2 numbers that add to given sum in an array.
Why the cover of a drainage system is always circular ?
Difference between overriding and overloading ?
Why the cover of a drainage system is always circular ?
Write a program to find 2nd last element in a linked list ?
Also change the code to find n-th last element in linked list ?
Design a class for a product, which has several promotional offers based on its buy weight. Input are: product-Rice,buy weight-105kg, provided the offer price are Rs.30/Kg, Rs.28 per 2Kg, Rs.25 per 5Kg, Rs.24 per 10Kg. Come out with an output that would quote the least price, and if there are 2 offers with the same price, the choice has to be made on the least number of baggages.
How much space does a pointer and integer takes?
For eg :-
int a;
int *a;
I told him that the take same amount of space but he was not convinced. Am i missing something??
Which data structure would you use to implement Phone book?
I told him about tries.
He asked me some other D.S and then he hinted me about hash table.
Then he asked about the difference between both the approaches and which one to use when? He specifically asked the advantages of both the approaches??
follow up ques:- Which data structure for Dictionary?
Which among tries and hashtable would you use for phone book and which one for Dictionary?
I answered that dictionary and phone book are same but he was not at all convinced..
How to find the shortest path to reach from one profile to another through friends in facebook.
Which is greated 3^20 or 2^30
Difference between MYISAM and NoDB Mysql
How will you match a find a substring in a given string.(Pattern Matching)
Write a C function to reverse a string given just two character pointers along with the input string.
Given an n-ary tree of resources arranged hierarchically. A process needs to lock a resource node in order to use it. But a node cannot be locked if any of its descendant or ancestor is locked. You are supposed to:
-> write the structure of node
-> write codes for
Islock()- returns true if a given node is locked and false if it is not
Lock()- locks the given node if possible and updates lock information
Unlock()- unlocks the node and updates information.
Codes should be :
Islock –O(1)
Lock()- O(log n)
unLock()- O(log n)
Find diameter of a binary tree in O(n)
Given 3 prime numbers and an integer k, find the kth number if all the nos which are having these 3 prime numbers as their factors are arranged in increasing order.
Eg. prime numbers - 2,3,5
The increasing sequence will be 2,3,4,5,6,8,9...
Design an event driven system.
Design a reliable communication for transaction based service. Any transaction performed by an application in distributed environment has to get committed with an external service.
Given two sorted arrays, find the median.
You have an array in which ever number is repeated odd number of times except one , you have to give that with O(n) time complexity
Q2 Sort a list of objects using the following comparison operator.
isGreater(a,b)
+1 a>b
-1 a<b
0 The previous comparison is annulled. //it means we back to prev position isn’t it ?
write code efficient sorting
Rank a list without sorting it.
List : [6, 3, 9]
Rank : [1, 0, 2]
algo & then code it efficiently
Where does constant strings resides in memory in c-programs....e.g:
char *ptr="hi Jacline";
Where do you see the smartphone industry moving? What needs to be done to make users to go in that direction?
How much would it cost to store all the videos in the internet? (Need to make good assumptions like no of video servers, file size/type/encoding etc)
Write a code to find distinct elements from a array containing elements in running form eg {111111111112222222222222333333333555} should give 1,2,3,5 as output.
Design a mechanism which can aquire lock on all the objects (More than 1) and attributes of a method with out using Synchronized method , synchronize block or volatile keyword .After that he asked me to implement the same on two two objects i.e. On a multithreaded environment we need to need to send data to printer as well as on screen (It should be in sync ) and if other thread is already using any of the resource then wait till the time when both the resources are available .
Given a stream of text eg you can read 1 char at a time, write fn that will return true if you can find a string str in the stream before the stream runs out
What if the string you are looking for is abc
And the stream is aaabababcab
I gave a solution using a stringbuilder ( like a circular array) but he didn’t like it. He wanted a solution that doesn’t require space equal to the string you are looking for
Given a modified BST where each node carries extra information of the total number of nodes below it. Find the Kth smallest number in O(logn) time.
Write a program to implement Boggle Game.
You are given a 4x4 matrix of letters and a dictionary, find all the valid words in the matrix. Following are the conditions
1. If a letter is used, it should not be used again in the same word search
2. The word path can be of any direction
3. There has to be a path of the letters forming the word( in other words all the letters in the word must have to adjacent to one another)
Example:
D A T H
C G O A
S A T L
B E D G
Some of the Valid words are:
DATA, HALO, HALT, SAG, BEAT, TOTAL, GLOT, DAG
Not valid words:
DAGCD ( D cannot be used again)
DOG ( There is no path between letters)I have given a back tracking algorithm and he did not like it
Given a sum and number of digits n. Find all the combinations of single digit numbers that are equal to sum. For example if sum=13 and n=2, one of the ans should be 6,7 and so on
a) There is a square of nxn size which is comprised of n-square 1x1 squares. Some of these 1x1 squares are colored. Find the biggest subsquare which is not colored.
b) Also asked to extend it to find the biggest area rectangle.
12
Suppose we can compare two arrays like:
{4,2,3} > {3,5,6}
{4,2,3} < {4,3,0}
In each move, you can only switch a number with one of its neighbor. Given an array and a number n, design an algorithm to make this array maximum using n moves. (needs clarification)
Given a n-ary tree. A random leaf node will be selected.Imagine that you are now holding the tree with your hand from that node. All other nodes will now fall under gravity. Write a function to perform this transformation.
Given an array which consists of elements in the following form :
->All the adjacent elements differ only by value -1 or +1.
->You are given an element. You need to search for its index.
Can anyone help me with this question?
Write an algorithm two divide two extremely large numbers, which cannot be stored in an int, long int, float, double etc. Find the remainder and quotient .
Notes:
1. Do not use the subtraction approach .
an MxN matrix is sorted both rowwise and coloumnwise.find kth minimum in the matrix efficiently.
implement a stack which will support three additional operations in addition to push and pop:
1.peekLowestElement()//return the lowest element in the stack without removing it from the stack
2.peekHighestElement()//return the highset element in the stack without removing it from the stack
3.peekMiddleElement()//return the (size/2 +1)th lowest element in the stack without removing it from the stack.
faster is better.Assume every method will be called with equal frequency.
We have a N X N matrix whose rows and columns are in sorted order. How effeciently can we find
the median of those N^2 keys ?
You are given a set of boxes b1 to bn. Each box bj has an associated width wj ,
height hj and depth dj . Give an algorithm for creating the highest possible stack of boxes with the
constraint that if box bj is stacked on box bi, the 2D base of bi must be larger in both dimensions
than the base of bj . You can of course, rotate the boxes to decide which face is the base, but you
can use each box only once.
For example, given two boxes with h1 = 5;w1 = 5; d1 = 1 and h2 = 4;w2 = 5; h2 = 2, you should
orient box 1 so that it has a base of 5x5 and a height of 1 and stack box 2 on top of it oriented so
that it has a height of 5 for a total stack height of 6.
construct a BST given its preorder traversal..No extra space allowed
Give two binary search trees, print the numbers of both together in ascending order.
Given a 2D matrix which is both row wise and column wise sorted. Propose an algorithm for finding the kth smallest element in it in least time complexity.
write floyd warshall algorithm
pairwise reversal of linked list..
eg.i\p=1->2->3->4->5
o/p=2->1->4->3->5
Input is a matrix of size n x m of 0s and 1s.
eg:
1 0 0 1
0 0 1 0
0 0 0 0
If a location has 1; make all the elements of that row and column = 1. eg
1 1 1 1
1 1 1 1
1 0 1 1
Solution should be with Time complexity = O(n*m) and O(1) extra space
Given an array A of N integers we draw N discs in a 2D plane, such that i-th disc has center in (0,i) and a radius A[i]. We say that k-th disc and j-th disc intersect, if $k\not =j$ and k-th and j-th discs have at least one common point.
Write a function
class Solution { public int number_of_disc_intersections(int[] A); }
which given an array A describing N discs as explained above, returns the number of pairs of intersecting discs. For example, given N=6 and
\begin{displaymath}A[0]=1 A[1]=5 A[2]=2 A[3]=1 A[4]=4 A[5]=0\end{displaymath}
there are 11 pairs of intersecting discs:
0th and 1st
0th and 2nd
0th and 4th
1st and 2nd
1st and 3rd
1st and 4th
1st and 5th
2nd and 3rd
2nd and 4th
3rd and 4th
4th and 5th
so the function should return 11.
The function should return -1 if the number of intersecting pairs exceeds 10,000,000. The function may assume that N does not exceed 10,000,000.
implement a func node *(char *word){}
wich returns a link list of words dat are anagrams with the input word..if no anagrams found return NULL and add that word to the link list
what does the yeild method do in case of a thread lifecycle ? Explain with a neat example demonstrating the use of yield method?
given a matrix with all 1,s or 0,s. find the square sunmatrix with all 1's at border.
ex:
0 1 0 1 0 1 1 1
0 1 1 1 1 1 1 0
1 1 0 1 1 0 1 1
0 1 0 0 1 0 1 0
0 1 1 1 1 1 1 1
so the submatrix from (1,1)to (4,6) is the answer
see it is not square but i have just wriiten to make it clear the ques .
given matrix will bee square matrix and we have find square submatrix as well
There is an array and the distance between any two consequent elements is one(+1 or -1) and given a number. You have to check whether the number is in array or not with minimum complexity.
Given preorder traversal , is it sufficient to reconstruct unique BST
Design algo and DS to find the minimum length of Fence required to cover scattered points (all co-ordinates given) in a plane.
given an infinite array containing only 0's and 1's in sorted manner. Give algo to find the position where first 1 appeared with minimum complexity (Interviewer gave hint to use random number generator algo, don't know why).
Find max diameter of circle placed inside the area surrounded by points (x, y) given that when points are joined they form a closed loop.
Given inorder traversal , is it sufficient to reconstruct unique BST
There are N points in the plane. The ith point has coordinates (xi, yi). Perform the following queries:
1) Reflect all points between point i and j both including along the X axis. This query is represented as "X i j"
2) Reflect all points between point i and j both including along the Y axis. This query is represented as "Y i j"
3) Count how many points between point i and j both including lie in each of the 4 quadrants. This query is represented as "C i j"
No O(n) solutions please.
Give two binary search trees, print the numbers of both together in ascending order
OO Design for parking lot system.
Given two lists, each containing numbers, how would you find the intersection of these two lists? What if these two lists are read from a huge file that cannot fit in memory?
You need to implement two functions of hashing
int get(int key) // will return value at key
void put (int key,int value) // put the vaue at index key
both functions should be of order O(1)
and there is an upper limit n on size, such that at the max only n elements will get stored and if there is a conflict then you need replace the least recently used element.
Code/Define Algorithm to find if a given string has balanced parentheses, where we have 3 types 1. ( ) 2. [ ] 3. { }. Example of Balanced - [{}](), Not balanced - ({)[}]
Given an array A[] and a integer num. Find four no.s in the array whose sum is equal to given num.
Brute force :- O(n^4)
I solved it in O(n^3)
But the interviewer was insisting on a better solution.
what is difference between union and structure ? what is padding in the context of structures
What is the difference between static and global variables in C.
Implement a function that performs binary addition. Input to the function is two const strings. The function returns a string that holds the result of addition.
char* binaryadd(const char* a, const char* b) { }
Eg. "1001"+"101"="1110"
What is the difference between HashSet and TreeSet implementation of a Set ?
Closest pair. Given an array of N real numbers, write a static method to find in linear time the pair of integers that are closest in value . Similarly find the farthest pair
Given a class Card{int value, int suit, Color color}, Write a method
Card[] GetUniqueElements(Card[] cards)which gives all the unique Card Objects .
Write a function to find the longest common prefix string amongst an array of strings
Given a number, convert it to minimal sum of squares.
N can be represent as “x^2 + y^2 + z^2” or “a^2 + b^2”. But here the exception is minimal i.e. the answer will be “a^2 + b^2”.
write a code which will receive as input a matrix (int[][] matrix) and which should find all local maximum from the matrix. A local maximum is such a number in the matrix that is greater than all its immediate neighbors. The method should return the List of locations of all local maximum numbers found.
write a program to find the largest word in a sentence, also incorporate error checking.
Given an array of integers for each elemnt in the array find the closest greatest elemnt to the right.
Closest means the distance beteen two elements array indices must be miminim . can it be done better 0(n2) ?
Find the element with the middle value among all elements of the stack...you can you extra space but complexity should be minimum
I need a solution that is not O(n3). I gave the O(n3) solution but the interviewer was not happy. We also cannot copy the input vector as space requirements in O(1).
A zero-indexed array A consisting of N integers is given. A triplet (P, Q, R) is triangular if and
A[P] + A[Q] > A[R],
A[Q] + A[R] > A[P],
A[R] + A[P] > A[Q].
For example, consider array A such that
A[0] = 10 A[1] = 2 A[2] = 5
A[3] = 1 A[4] = 8 A[5] = 20
Triplet (0, 2, 4) is triangular.
public int triangle(int[] A)
that, given a zero-indexed array A consisting of N integers, returns 1 if there exists a triangular triplet for this array and returns 0 otherwise.
Assume that:
N is an integer within the range [0..100,000];
each element of array A is an integer within the range[-2,147,483,648..2,147,483,647].
For example, given array A such that
A[0] = 10 A[1] = 2 A[2] = 5
A[3] = 1 A[4] = 8 A[5] = 20
the function should return 1, as explained above. Given arrayA such that
A[0] = 10 A[1] = 50 A[2] = 5
A[3] = 1
the function should return 0.
Expected worst-case time complexity: O(n log n)
Expected worst-case space complexity: O(1)
I was asked to design a data structure for a phone address book with 3 fields
name, phone number , address
one must be able to search this phone book on any of the 3 fields .
Write a function to check if the two strings given are anagrams are not. here AAbCDE and DECbAA are anagrams.Also, ABC and BCA are anagrams. however, AABBC and CBBAA are not anagrams.
Write a program to count the number of columns given the sample hitml like below:
<TABLE BORDER>
<CAPTION>A test table with merged cells</CAPTION>
<TR><TH ROWSPAN=2><TH COLSPAN=2>Average
<TH ROWSPAN=2>other<BR>category<TH>Misc
<TR><TH>height<TH>weight
<TR><TH ALIGN=LEFT>males<TD>1.9<TD>0.003
<TR><TH ALIGN=LEFT ROWSPAN=2>females<TD>1.7<TD>0.002
</TABLE>
On a dumb terminal, this would be rendered something like:
A test table with merged cells
/--------------------------------------------------\
| | Average | other | Misc |
| |-------------------| category |--------|
| | height | weight | | |
|-----------------------------------------|--------|
| males | 1.9 | 0.003 | | |
|-----------------------------------------|--------|
| females | 1.7 | 0.002 | | |
\--------------------------------------------------/
Given a filename say filter_file.c , program to search for any pattern in order
ex flt_fl -. true
flt_el - false
search text is in order and characters occur multiple. any permutation. unwanted characters not allowed.
exact code for postorder traversal of tree without use of recursion.
structure of tree is:
struct btree
{
struct btree*left;
int*data;
struct btree*right;
}
Find inorder successor and predecessor of a given node in BST. Root node is given.
all cases should be include in single function.
Design classes to calculate the price of a pizza with different crusts, toppings and sauces
Design and create a Collections library. Make it flexible from two aspects
Given a set of strings, check whether it is possible to chain all of them. Two strings can be chained iff s1[n] == s2[0] || s2[0] == s1[n]
OO Design for a restaurant reservation system
Design a DFS that supports mount, open, read, write, close and unmount
print presence of a string in MxN alphabet grid
what about single-order APIs, eg: loadOrder(orderId)
How would you architect an online website?
Void xyz(char a[10])
{
int i;
i=sizeof(a);
printf("%d",i);
}....its o/p is 2..wats d logic behind it..
How to find duplicate element (only one element is repeated) from an array of unsorted positive integers..
time complexity .. O(n)
space .. o(1).
Sort an array of n positive integers containing n/2 sorted integers in first and second-half?
in O(n) time complexity ..
and space complexity should be constant
write a class Tool which will have a function void type() that every derived class should implement . A function Action() that every derived class can override . function init() which is available to only Tool and variable Name which will tell which class`s instance is this object
Write a poker function which will take an array of 5 ints and will return true if 2 elements and 3 elements are equal
for ex . 10 5 10 5 5 returns true
5 10 10 10 5 returns true
1 5 10 10 10 returns false
1 2 3 4 5 returns falseYou are provided with three lists:
1- Maximum no. of questions of a type.
2- Mark per question of each type.
3- Time required to solver per question.
For a given cutoff, find the solution in terms of minimum time required to get over this cut off(in minimum no. of questions preferably) ?
# define swap(a,b) temp=a; a=b; b=temp;
main( )
{
int i, j, temp;
i=5;
j=10;
temp=0;
if( i > j)
swap( i, j );
printf( "%d %d %d", i, j, temp);
}....its o/p on turbo c is 10 0 0..can any 1 explain the logic
How would you design a software like Microsoft Excel? Basically, the interviewer wanted to know how I would store the cells and the relationship between cells. For examples, let there be 4 cells, A1, B1, C1 and D1.
Let values of the cells be following:
A1 = 10
B1 = A1 + 3
C1 = A1 * 2
D1 = C1 + B1
In this case, how would I store relationship between cells and if I make a change in A1, how would that propagate to other cells.
Can anyone tell me about the written test of Adobe . I will be greatly thankful to him
Tell about the differences between Microsoft's COM and Java RMI.
Design an algorithm for chatting between two clients. What about your procedure's scalability?
Find an anagram do it in 0(n+m) complexity.
Given a Binary tree find total number of clusters in a binary tree.
Cluster Definition: Assume there are two colors of node RED and BLUE. A start of cluster is when root, left and right have same color Node.
Partition a set of numbers into two such that difference between their sum is minimum, and both sets have equal number of elements.
For example: {1, 4, 9, 16} is partitioned as {1,16} and {4,9} with diff = 17-13=4.
Does greedy work here? First sorting, and then picking smallest and largest to fall in set 1, and picking 2nd smallest and 2nd largest to fall in set 2.
I was asked to prove which I failed :(
What is wrong with following code?
#include<cstdio>
using namespace std;
class Lock {
public:
Lock():isLooked(false) { }
bool AcquireLock() { return isLooked ? false : (isLooked=true);}
void ReleaseLock() {isLooked = false; }
private:
bool isLooked;
};
template <typename T>
class Singleton {
private:
static Lock lock;
static T* object;
protected:
Singleton() { };
public:
static T * Instance();
};
template <typename T>
T * Singleton<T>::Instance(){
if (object == 0) {
if(lock.AcquireLock()){
object = new T;
lock.ReleaseLock();
}
}
return object;
}
int main() {
int* singleton_foo = Singleton<int>::Instance();
return 0;
}Given multiple sorted list, merger them into a new sorted list.
The interviewer first asked for algorithm and time complexity.
Then he asked me write code in a paper and then read to him.
How to add two sparse polynomials ?
Find Height of a tree without using recursion ?
Given an acyclic undirected unweighted connected graph, find its representation as a tree with the least height. Brute force is O(n^2). Come up with an O(n) solution
Design a queue (FIFO) using only stacks (LIFO). The only supported operations on the stack are: Push(), Pop() and IsEmpty(). The final queue had to implement the operations Queue() and Dequeue(). The program had to be efficient and handle exceptions.
Design an algorithm to sort an array whose first n-sqrt(n) elements are already sorted. What is the complexity of the algorithm.
Design an algorithm to find all elements that appear more than n/2 times in the list. Then do it for elements that appear more than n/4 times.
Given an set of n integers and an integer x. Design an algorithm to check whether k integers add up to x in the given set.
The complexity should be O(n^(k-1) * logn)
Design an algorithm to perform operation on an array
Add(i,y)-> add value y to i position
sum(i) -> sum of first i numbers
we can use additional array O(n) and worst case performance should be O(log n) for both operation
Q1) Write a program to calculate height of a binary tree non - recursively ?
Q2) Asked which data structure should be used to store browser history.
Q3) Find the anagrams with a huge list of words .
Q4) Mirror a tree iteratively.
Q5) Compute a+bx2+cx3+dx4+... efficiently (a,b,c...given)
Q6) Find one missing alphabet in an array of 26 alphabets(one alphabet repeated twice).
There are 3 friends say A, B, C. Of them, C knows one of A/B speaks always the truth and the other speaks always lies. One day, all of them meet with a car accident. Unfortunately, both A and B die on the spot, and C joins them a bit late. When C reaches the alien world, he wants to goto heaven. He only sees 2 exits. So, he assumes one exit for heaven and the other exit for hell. He also recognizes both A and B as security guards standing at each of the exits. Now, knowing one of A/B speaks truth and the other lies always, C needs to find way to heaven, by asking only ONE question to each of the security at the exits? How?
Object oriented design to implement Kindle's Whisper feature.
What is the time complexity of this program?
a[0..(n-1)] = array containing numbers from 0 to n-1 in random order
leftExtreme = a[0]
rightExtreme = a[0]
ctr=0;
for(i=1 to n-1) {
if(a[i] < leftExtreme) {
leftExtreme = a[i];
for(j=a[i] to leftExtreme) {
ctr++;
}
}
else if(a[i] > rightExtreme) {
rightExtreme = a[i];
for(j=rightExtreme to a[i]) {
ctr++;
}
}
}
Dramatic - You need to find if a given sentence (a line of text) is available in a given magazine. You can not reuse letters. Think like, you are asking for some ransom, putting someone at gun point.You grab a magazine (weekly) and start tearing/cutting letters to form the sentence "I want blah blah money". Write a function that tells the given magazine has all the letters/alphabets sufficiently to form the sentence.
Given millions of time intervals, compute the maximum weights and the time when maximum weights occurred.
Time interval is defined as followings (s: starting time, e: ending time, w: weight). And pls note that s, e, and w are not necessary integer.
// find the pair in an array .... that sum up to particular number
I have two methods of an object, and they each access a critical section of code. I want to restrict access to the section so that in one method, I allow multiple threads to access the critical section. In the other method, I want only one thread to have access. If a caller calls the second method, it should lock out all clients from accessing the critical section in either of the two functions. Here is the basic structure of the class:
class ClassThatNeedsFixing
{
public:
// Will allow many concurrent threads through, unless there is a
// call to the other method.
void AllowMany() {
// Here is the critical section that must be protected
...
}
// Will lock out any client, including callers to the other method.
void AllowOne() {
// Here is the critical section that must be protected
...
}
private:
// Assume there are members here that need protecting
// above.
...
};
In order to solve this problem, you are provided with two classes: Mutex and Semaphore. They have the standard behavior of the concepts that share their class names. Here are the public interfaces for each of these classes:
class Mutex
{
public:
Mutex();
void Acquire();
void Release();
};
class Semaphore
{
public:
// At it's creation, one can specify the count
// of the semaphore.
Semaphore(unsigned int count);
void Acquire();
void Release();
};
Fix the ClassThatNeedsFixing implementation so that the critical section is protected.
Your solution will be graded on flexibility and robustness (i.e., we should be able to re-use your solution in a generic case and it should be exception safe). You are allowed to create as many classes/objects/templates/etc that you need. Feel free to use the STL if necessary. Document your code as you would for real-world maintainability.
A common problem is to generate the intersection of two sequences. A sequence is a sorted list of objects that are ordered according to some comparison operation. I need two functions (or one function with some type of switch parameter) that provide an intersection of two sequences. In one case, I want to only output an intersection of the sequence, but if there are duplicate values in the sequence, only output one object. In the other, preserve duplicates. For example, take two sequences:
A: 1, 3, 3, 7, 7, 7, 8
B: 2, 3, 7, 7, 9
The output in the non-duplicate preserving case should be: 3, 7. For the duplicate preserving case, the output should be: 3, 7, 7.
Your solution will be graded on flexibility, robustness, and scalability. You are allowed to create as many classes/objects/templates/etc that you need. Document your code as you would for real-world maintainability. You can use STL concepts, but the STL is unavailable to you.
The definition of a sequence and/or iterating through a sequence is not provided to you as part of this test question. It is up to you to determine how you want callers to pass in a sequence and how the caller will receive output. The solution should be flexible enough that the caller can easily adhere to a sequence definition, and once you have specified the API, assume that callers will provide a sequence in sorted order. If the caller does not adhere to your pre-conditions, it is the caller's fault, not yours (i.e., you don't have to test that a sequence is sorted). But, do try and make it easy enough for a caller to reuse.
How to set up a LAN
Find two numbers(a and b) from integer array such that a + b = x, where x is input along with array. I have solution with o(n^2) with linear/brute force. But i was just wondering can we do it in n*log n or n or just log n.
P.S. No range specified for numbers for array. We need very general solution
Given an array of unsorted integers , how to find duplicates in O(n)
Jump Game:
Given an array start from the first element and reach the last by jumping. The jump length can be at most the value at the current position in the array. Optimum result is when u reach the goal in minimum number of jumps.
For ex:
Given array A = {2,3,1,1,4}
possible ways to reach the end (index list)
i) 0,2,3,4 (jump 2 to index 2, then jump 1 to index 3 then 1 to index 4)
ii) 0,1,4 (jump 1 to index 1, then jump 3 to index 4)
Since second solution has only 2 jumps it is the optimum result.
implement a telephone directory where you have to associate each person with a phone number.
difference between release build and debug build. Did you hear about memory leaks? how do they occur?
write a function to return the number of bits set in the given byte.
skills assesment test had more or less similar kind of questions posted here. Other tests included some peculiar math test which had some really peculiar ques....Neway, the interview left a bad taste in my mouth....after doing everything pretty well in onsite...they still rejected me...God knows on what basis do they hire !
If we contact your references, what strong qualities would each one of them tell about you, also what areas would they say you need improvement.
write paranthesis matching code and to find palindrome .
3 divides 111 , 13 divides 111111 etc.. find a number having all one's which is shortest divisible by a given number which has 3 as its last digit.
n=4 and k=3 . team name can be formed by four digits 1,2,3,4 . so n=4 now make team number using any three digits so that b1<b2<b3. Basically print numbers which are in form b1<b2<b3..e.g. 123,124,234 etc
How many child processes will be generated by the following?
void main() {
int p1= fork();
if (p1 == 0) {
int p2 = fork();
if (p2 != 0) {
fork();
}
}
}
A "Most efficient data structure" is designed to optimize the following operations. Pop, Push, Min. The best possible time-complexities with no extra space, respectively would be?
Write a function that takes an input string and a pattern string and returns a collection of indices of occurences of pattern within the input string.
A test plan and cases for a highway system that has three components: (a) a camera that takes pictures of vehicle license plates (b) an embedded system that sends the image taken by the camera and send it to (c) some OCR... link server that actually processes the image and sends details to DMV ticketting system
* What exactly I work and my responsibilities
* How do I approach improving efficiency and testing plans
Given two arrays
a[] = {1,3,2,4}
b[] = {4,2,3,1}
both will have the same numbers but in different combination.
We have to sort them . The condition is that you cannot compare only
elements within the same array.
Given a number N find the next number M which is greater than N and the difference between M and N is small and M consists of same digits as N ! i.e M is an anagram of N ...
Example : 678 -- Ans=687
52430 -- Ans=53024
if number is 876 ans=no solution
will abstract class creates virtual table or not?
Convert the BST to sorted doubly linked list , don't use additional data struct.
Print the M*N matrix in spiral manner.
Write a C code to find Leftmost right cousin at the same level.
For ex:
10
/\
2 3
/\ /\
8 56 9
Leftmost right cousin of 5 is 6. Leftmost right cousin of 3 is NULL.
Reverse link list using recursion.
Write a algo for implementing the word prediction for MS word.
Write a validate function for sort API , which cover all the validations for sort . Not particular about lines of code, but looking for varieties , and logic of the code.
result of this:
select *
from A, B;How do you make variables public, private, or protected in Perl?
Program to check validity of an email id.
Find the largest and smallest element in binary tree/binary search tree at level n.
Write test cases for smple TFTP program.
Describe the difference between $_ and @_ .
result of this:
main()
{
fork();
fork();
fork();
printf("hello\n");
}Given string input1, input2, remove wherever the occurrence of input2 in input1.
e.g:
input1: skjthshetheshetesm
input2: she
input1 will become "skjththetesm"
Give the test cases.
given an array , find three numbers a,b and c such that a^2+b^2=c^2 ..
I have given algo of o(n^2) complexity. But he is expecting still better algo.
The 2020 is a number where index value is equal to number of times occurrence of index in number. for eg: for 2020
index(0)=2 (as 0 occured 2 times in 2020)
index(1)=0 (as 1 occured 0 times)
index(2)=2 (as 2 occured 2 times)
index(3)=0 (as 3 occured 0 times)
Now input given is a number, determine whether the given number posses property same as 2020 (given as example in above question)
This was the technical question in the recent interview..Print a n*n matrix in spiral order and what will be the consequences(if u use recursion) in case of larger matrices like 10000*10000..
Given a binary tree and head node, write a function that takes head node and some node as input and returns leftmost right cousin of it.
ex:
1
/ \
2 3
/ \ / \
3 4 5 6
for the above tree if node 4 is given as input then the function should return 5 as output.
In an array find out the nth maximum number.
Given an unsorted array. How to find out the maximum number.
Then how to do it in minimum number of comparisions
Then how to find out the second largest number
Asked me what is heap corruption.
Process n threads.
What threads share with each other.
How will you implement your own garbage collector in C.
There is a 2d matrix and in each point there are some gold coins.
Then starting from the bottom left point you have to collect the maximum number of points. The constraint is that you can only move in right and up direction.
Then asked me to optimize it
After that do it using recursion
Compare the two methods
Give a mathematical formula for this problem.
Lowest common ancestor of bst
After that modified it for binary tree
Given a large string . then you have to find out largest string such that all its character are consecutive . Asked me to write a neat C code for this problem.
Maximum contigous subarry for one dimensional array
After that modified this question for 2d array. Find the biggest square or rect matrix such that sum is max.
This round was focused on DS only
Reverse a link list
Gave me a link list in which loop is there. What will happen if we reverse such a kind of LL.
Detect loop in LL
Starting node at which loop is starting
WAP to check a tree is symmetric.
WAP to reverse pair of nodes in linked list
find third largest element of a array in a single pass?
Given an array of integers. Each number in the array repeats ODD number of times, but only 1 number repeated for EVEN number of times. Find that number.
Given an array of integers. Each number in the array repeats even number of times, only 1 number repeats odd number of times. Find that number.
How the find the kth last element in a linked list?
Create a structure that will allow you to search a person by first name or last name (or both), in better than O(N) timeframe.
What is wrong with this program :
main()
{
char *p,*q;
p=(char *)malloc(25);
q=(char*) malloc(25);
strcpy(p,"amazon" );
strcpy(q,"hyd");
strcat(p,q);
printf("%s",p);
}
A function GetWordFromList takes an integer parameter and returns the word at the corresponding index. Now you are given a word,say "string", how do you optimally get the index of the word where it occurs. You don't know the data structure used to store the words.Assume that all the words in list/database are sorted.Also assume that the function returns null or some exception if the index which is given as input is out of bound
How do you go about finding the top 10 google searches at the end of a day? In case you are storing the information about them, how and where would you store it? (like disks etc)
Given a sorted array, output all triplets <a,b,c> such that a-b = c. Expected time is O(n^2). My approach using binary search took O(n^2 logn). When you attempt an approach, test your code with this example and list your outputs for verification. Thanks.
-12, -7, -4, 0, 3, 5, 9, 10, 15, 16
This was a question asked in an onsite interview with amazon. The interviewer had to be the bar raiser because every other question was pretty easy.
given a number, come up with all of the possible ways to insert '+' and '-' in that number. for example given 123, possible answer would be
1+23
1+2+3
1-23
1-2+3
1-2-3
1+2-3
12+3
12-3
Given an array containing elements 1..N but containing repeated elements.we have to find the missing element..No extra spaces allowed and time complexity should be O(n).
Given a binary tree we have to update another pointer sibling in the node such that every node sibling is the left node of current node.If there is no left node then its sibling should point to the right most node at that level...!!
Design an algorithm such that we have to find the k th element in the array such that their only prime factors are 3,5 an 7.
Example: Array will contain 1,3,5,7,9,21,25,...
We have to return the kth element in array...!!!
round 2:
1. explain me final, finally and finalized in java. (on JAVA)
2. 2. you have unsorted array[n] elements. the numbers in the array[n] occurs event times except one number occurs odd time. So, write an algorithm to find that number. Also explain its complexity too. (time and space) both. (On ALGORITHM)
3. you have html page directory. in each html page u have written name and phone number. now you have to make normal directory from that information. write an algorithm that convert html directory to normal directory.
3. tell me the class design of playing cards for any game.
2. what is the time and space complexity of above algorithm. It is the best approach ?
1. you have array[n-1] elements and you have 1 to n numbers. now you have to find one missing number in array[n-1]. Write an algorithm to find that missing number.
How can make Mutex global to All CPUs in your Board? Because spinlock is global to all CPUs in SMP system. Just make Mutex work like spinlock?
Write an algorithm to find the first non-repeated character in a string using O(1) space and O(n) time. you can only use 1 bit space for each character.
When people search at Google, they often type two words without space. For example, instead of typing "binary tree", someone can type "binarytree". Given an input, what is a good way of finding if it is a combination of two valid words?
find the intersection point of 2 linked list (without hashing at a lesser complexity preferably O(m+n))....
..(the 2 nodes from the seperate lists point to a same node from which the list continues as a single list)
what is "type equivalence" and "structure equivalence"? how does C support both of them?
can someone explain me native file system(NFS)???..
three points are randomly chosen on a circle.what the probability that
1.triangle formed is right angled triangle.
2.triangle formed is acute angled triangle.
3.triangle formed is obtuse angled triangle.
given a set of letters and a length N, produce all possible output.(Not permutation). For example, give the letter (p,o) and length of 3, produce the following output(in any order you want, not just my example order)
ppp ppo poo pop opp opo oop ooo
another example would be given (a,b) and length 2
answer: ab aa bb ba
how can we calculate the time complexity of recursive problems??
I am having online test for Amazon SDE can anyone help ??
design a data structure that can do all four operationm in O(1) e.g. constant time
1.insert()
2.delete(0
3.search()
4.random() this generate only that random number that are inserted in data structure & it has be in O(1)
how to copy passwords from gtalk box
how to write test cases for backspace
Let's say you have a phrase without any spaces - eg. "thisisawesome". Given a dictionary, how would you add spaces in this string?
1- reverse a pair of elements in a linked list. abcd - badc
2 - find 3rd largest in an array in single pass
3 - check if a tree is symmetrical
Given a Binary Tree ( Comprising of +ve & -ve numbers ), represent each node of the tree with sum of its LeftSubTree & RightSubTree
For Example :-
10 | 20
-2 6 | 4 12
8 -4 7 5 | 8 -4 7 5
Given a Doubly Linked List comprising of 1,2,3 nodes only. Write Code to Sort it.
Given a Binary Tree, Convert it into Doubly Linked List where the nodes are represented Spirally.
For Example :-
A
B C ----> ABCGED || ACBDEG
D E G
Print triplets that sum to 0 in an integers array
Round 4 :
1)Why Amazon?
2)Talk about any software related work of yours that you are really proud of.
3)Weakness & Working on getting out of it.
4)Given a preorder traversal construct a binary search tree. Time complexity of average case in particular. Since I said binary search
can be applied, I was asked about using that algorithm and find if the time complexity has improved.
And of course, the last question- Any Questions?
Round 3 : Coding Skills .
Tell me about yourself.
Explain any of your projects
1) You are given a singly linked list. On seeing a node, if it has a node with greater value than itself on its right delete it. Return the head of the result singly linked list.
2) Find the maximum sum subsequence in an array with positive nos such that no two nos are adjacent.
Should explain code, write the code with base conditions properly, and give all possible test cases.
Round 2 : Problem solving skills
Tell me about yourself.
1) Design an API for this scenario. There is a one time input of a set of data. The user works on a interface that has two options-
a) Find(x) which returns x if found.
b) Findkthmin()
This interface is used several hundred times a day. Describe the data structure& algorithm that you will use.
2) What is a stack- what is the time complexity of push()&pop(). Define another operation findmin() on the stack efficiently.
3) Given a rectangle of dimensions b*h, and a input no N, find the size(side length) a such that N squares of size a can fit into the rectange. Optimize based on the minimum wasted of space in the rectangle b*h
Was not asked to write the code, only the algorithm.
Thanks to careercup that gave me an exposure to amazon qns. My interview experience.
1st was an online round for 90 mins- 2 sections each with a min cut off for selection.
Section 1 : 20 multiple choice qns.
Section 2 : coding- There was a compile &test option, after ensuring that the code really works,we can submit!
a)How will you add two nos represented as a singly linked list ( 2->9->1->7+5->1->7= 3->4->3->4 )
b) reverse a doubly linked list
eBay coding interview question really sucks and unreasonable. After I finished it, I realized that it was in the Internet. Which means if you google the question well, you can finish in 10 min. This cannot tell your coding skill at all. It tests your googling skill.
Given N pens and n caps . Sort them. you cant compare pens with other pens and caps with other caps
let f(n, k) be the # of ways of choosing k integers without replacement from
n consecutive integers so that no two selected are consecutive.
a. give a recurrence for f(n, k)
b. efficient implementation of f(n, k)
what is triggering in sql
Write a C program to print semicolon without using semicolon, even in your program.
I did this
#define SEMI ;
given machines[] where machine[i] denotes number of jobs ith machine can do. and
jobs[] is given ,where job[i] is the length of the ith job;
write algo to find minimum time required to complete jobs;
Assumption: Total number of jobs is equal to sum of machines[i]
We have two sorted int arrays
a[] --> size N --> contains N elements
b[] --> size 2N --> contains N elements, and N vacant locations
Write an algorithm of complexity O(n) such that b[] contains elements of a[] and b[] in ascending order.
Find all the pairs of integers whose sum is S in an int array.
We have two int arrays, find duplicate among them.
write code to serialize and deserialize a tree.The nodes contain string instead of data part. the lenght of string can be anything(not fixed).
j=(++i)+(++i)+(++i), i=2, j=? (please exlain)
Design a web crawler that will crawl for links(urls).
Welcome - congratulations on being selected to continue your application to join the engineering team here at FutureAdvisor.
A small number of applicants make it this far in the process.
This next stage, which is the final stage before in-person interviews at our offices in Pioneer Square in Seattle,
is a programming problem to be completed on your own time.
Note that we expect this problem to take only a couple hours,
but you can take as long as you wish (just let us know if it'll be more than a week).
This problem is language agnostic - feel free to use whatever you're most comfortable with.
The accompanying text file gives the historical prices, by month, of 28 different stocks and mutual funds
(from now on we'll call them both securities and make no distinction) for the time period Nov 2000 to Nov 2010.
The format is the following:
<Security Name> | <Security Symbol> | <array of historical prices per share>
The array of historical prices per share is in chronological order,
meaning that a[0] is the oldest price and a[119] is the most recent price.
The problem is the following: imagine an investor is selecting securities for his or her portfolio,
and wants to know which securities have had the most spectacular periods (i.e. "bursts")
of growth over the last 10 years. Formally defined, we're asking you to examine the historical
data of each security in the Data File, and determine for each security the single time period
where it had the biggest percentage gain in price. This could be a time period of 1 month,
some span of several months, or even the entire 120 months, depending on the security.
Your program should output the securities in order, from those with the biggest bursts
(in terms of percentage gain) to those with the smallest, and give both the time period
and the return (change in price over initial price) for each.
Please feel free to ask any questions that come up while you're working on this.
There are several ways to approach the problem, so don't feel that there's only
one way to solve it, but of course be ready to talk about possible efficiencies
and inefficiencies of your chosen implementation.
When you're done email your solution (either the single file or a zip if it's multiple)
to hackers@futureadvisor.com. We respond to most submissions within 1-2 business days,
and as appropriate will schedule interviews immediately.
Best of luck. We look forward to seeing your work.
Microsoft Corporation | MSFT | [17.47, 24.6, 23.77, 22.03, 27.29, 27.87, 29.41, 26.66, 22.98, 20.61, 23.42, 25.86, 26.69, 25.66, 23.5, 24.29, 21.05, 20.51, 22.03, 19.33, 19.77, 17.62, 21.54, 23.23, 20.83, 19.12, 19.15, 19.57, 20.67, 19.89, 20.72, 21.34, 21.43, 22.47, 21.25, 20.9, 22.24, 22.47, 21.56, 20.26, 21.24, 21.32, 23.21, 23.16, 22.25, 22.54, 22.8, 24.36, 24.28, 23.88, 22.93, 22.03, 23.06, 23.59, 22.71, 23.41, 25.11, 23.59, 23.56, 25.45, 24.05, 25.89, 24.79, 25.11, 22.28, 20.98, 21.58, 22.29, 23.89, 25.43, 26.69, 27.39, 27.86, 28.79, 26.37, 26.09, 28.03, 28.82, 27.68, 27.23, 27.08, 27.77, 34.69, 31.77, 33.66, 30.83, 25.82, 26.94, 27.07, 26.98, 26.21, 24.5, 26.1, 25.53, 21.36, 19.47, 18.72, 16.47, 15.66, 17.81, 19.64, 20.38, 23.19, 22.95, 24.19, 25.24, 27.21, 28.99, 30.04, 27.77, 28.39, 29.0, 30.24, 25.66, 22.89, 25.67, 23.47, 24.49, 26.67, 26.95]
Apple | AAPL | [7.44, 10.81, 9.12, 11.03, 12.74, 9.98, 11.62, 9.4, 9.27, 7.76, 8.78, 10.65, 10.95, 12.36, 10.85, 11.84, 12.14, 11.65, 8.86, 7.63, 7.38, 7.25, 8.03, 7.75, 7.16, 7.18, 7.51, 7.07, 7.11, 8.98, 9.53, 10.54, 11.31, 10.36, 11.44, 10.45, 10.69, 11.28, 11.96, 13.52, 12.89, 14.03, 16.27, 16.17, 17.25, 19.38, 26.2, 33.53, 32.2, 38.45, 44.86, 41.67, 36.06, 39.76, 36.81, 42.65, 46.89, 53.61, 57.59, 67.82, 71.89, 75.51, 68.49, 62.72, 70.39, 59.77, 57.27, 67.96, 67.85, 76.98, 81.08, 91.66, 84.84, 85.73, 84.61, 92.91, 99.8, 121.19, 122.04, 131.76, 138.48, 153.47, 189.95, 182.22, 198.08, 135.36, 125.02, 143.5, 173.95, 188.75, 167.44, 158.95, 169.53, 113.66, 107.59, 92.67, 85.35, 90.13, 89.31, 105.12, 125.83, 135.81, 142.43, 163.39, 168.21, 185.35, 188.5, 199.91, 210.73, 192.06, 204.62, 235.0, 261.09, 256.88, 251.53, 257.25, 243.1, 283.75, 300.98, 304.18]
Home Depot | HD | [38.22, 40.32, 35.56, 36.09, 39.44, 41.28, 39.59, 42.21, 38.54, 32.18, 32.07, 39.17, 42.83, 42.06, 41.99, 40.86, 38.98, 35.04, 30.91, 25.99, 27.72, 22.0, 24.34, 22.25, 20.29, 17.66, 19.81, 20.64, 23.83, 27.52, 28.11, 26.48, 27.3, 27.09, 31.53, 31.27, 30.25, 30.23, 30.94, 31.9, 30.05, 30.67, 30.13, 28.86, 31.36, 33.63, 35.24, 35.89, 36.74, 35.46, 34.4, 32.95, 30.48, 33.91, 33.6, 37.59, 34.92, 33.03, 35.54, 36.27, 35.14, 35.2, 36.59, 36.85, 34.79, 33.21, 31.31, 30.36, 29.99, 31.86, 32.8, 33.56, 35.49, 36.01, 34.99, 32.66, 33.67, 34.55, 35.18, 33.23, 34.47, 29.19, 28.35, 25.91, 24.44, 27.8, 24.09, 25.6, 26.36, 25.05, 21.62, 22.0, 25.03, 24.1, 21.96, 21.51, 21.66, 20.26, 19.65, 22.44, 25.07, 22.06, 22.72, 24.94, 26.24, 25.82, 24.32, 26.52, 28.28, 27.38, 30.49, 31.85, 34.69, 33.34, 27.83, 28.27, 27.82, 31.68, 30.9, 30.71]
General Electric | GE | [35.51, 34.06, 34.44, 31.12, 36.08, 36.43, 36.43, 32.44, 30.5, 27.87, 27.28, 28.84, 30.16, 27.96, 29.11, 28.28, 23.85, 23.54, 22.1, 24.5, 22.94, 18.88, 19.34, 20.78, 18.8, 17.86, 18.71, 19.84, 22.91, 22.33, 22.46, 22.27, 23.16, 23.49, 22.86, 22.59, 24.57, 26.67, 25.95, 24.36, 23.9, 24.83, 26.01, 26.69, 26.32, 27.12, 27.55, 28.56, 29.65, 29.35, 28.78, 29.48, 29.59, 29.82, 28.5, 28.38, 27.65, 27.88, 28.08, 29.58, 29.23, 27.31, 27.61, 29.22, 29.06, 28.78, 27.9, 27.67, 28.83, 30.09, 29.93, 30.08, 31.96, 30.96, 30.22, 30.61, 31.9, 32.53, 33.37, 33.79, 33.89, 36.34, 36.13, 33.61, 32.81, 31.3, 29.6, 33.06, 29.21, 27.44, 24.11, 25.55, 25.38, 23.34, 17.86, 15.72, 15.11, 11.32, 8.17, 9.71, 12.15, 12.94, 11.35, 12.97, 13.46, 15.99, 13.89, 15.6, 14.83, 15.76, 15.84, 17.95, 18.6, 16.13, 14.31, 16.0, 14.37, 16.25, 16.02, 15.95]
PowerShares QQQ Trust ETF | QQQQ | [56.43, 62.15, 45.86, 37.84, 44.61, 43.23, 44.17, 40.36, 35.41, 28.01, 32.77, 38.32, 37.61, 37.22, 32.65, 34.85, 30.67, 29.04, 25.23, 23.05, 22.7, 20.03, 23.73, 26.79, 23.56, 23.62, 24.32, 24.41, 26.53, 28.79, 28.95, 30.74, 32.27, 31.34, 34.0, 34.2, 35.25, 35.84, 35.36, 34.66, 33.62, 35.34, 36.49, 33.74, 32.9, 33.98, 35.68, 37.83, 38.97, 36.51, 36.33, 35.7, 34.15, 37.17, 35.94, 38.67, 38.09, 38.56, 37.98, 40.3, 39.58, 41.14, 40.26, 41.1, 41.02, 38.05, 38.03, 36.39, 38.12, 39.89, 41.79, 43.22, 42.41, 43.3, 42.58, 42.8, 45.19, 46.61, 46.84, 46.77, 48.09, 50.61, 54.18, 50.51, 50.48, 44.48, 42.33, 43.12, 46.56, 49.32, 44.58, 44.87, 45.52, 38.43, 32.48, 28.76, 29.41, 28.74, 27.23, 30.04, 33.96, 35.05, 36.09, 39.13, 39.71, 41.95, 40.67, 43.25, 45.5, 42.56, 44.52, 47.95, 49.03, 45.4, 42.61, 45.7, 43.36, 49.07, 52.18, 52.22]
Fidelity Investment Trust: Fidelity Latin America Fund | FLATX | [48.65, 46.08, 51.09, 51.74, 48.99, 46.91, 51.83, 51.34, 46.32, 45.76, 41.01, 40.98, 37.84, 38.65, 32.08, 27.64, 25.43, 26.63, 27.05, 25.74, 27.58, 41.75, 53.06, 58.08, 64.21, 68.87, 63.62, 57.18, 60.4, 56.37, 59.6, 59.08, 62.95, 56.74, 50.21, 52.2, 51.36, 50.33, 45.07, 42.68, 40.56, 41.99, 41.47, 38.93, 36.95, 34.59, 34.33, 33.51, 32.56, 31.58, 36.36, 33.82, 33.87, 33.78, 28.73, 28.09, 25.73, 26.84, 23.27, 21.91, 20.79, 19.77, 18.44, 18.98, 20.73, 18.41, 18.51, 17.07, 15.6, 15.13, 14.03, 13.48, 13.1, 12.63, 12.66, 14.24, 13.88, 13.26, 13.12, 11.87, 11.35, 10.75, 10.47, 9.97, 9.58, 9.34, 9.05, 7.79, 7.37, 7.61, 7.91, 7.63, 7.43, 6.59, 7.96, 7.3, 8.78, 10.07, 10.7, 10.89, 10.45, 10.06, 9.98, 9.11, 8.46, 8.23, 9.72, 10.04, 10.65, 10.85, 10.37, 9.87, 10.8, 11.94, 10.62, 9.82, 11.22, 11.67, 12.47, 12.13]
Fidelity Magellan Fund | FMAGX | [58.84, 62.91, 68.46, 67.44, 63.25, 61.4, 64.21, 61.53, 58.35, 61.7, 58.59, 57.35, 52.73, 53.46, 50.33, 44.27, 38.87, 42.06, 45.49, 43.37, 48.91, 62.39, 76.05, 76.11, 79.23, 86.47, 83.9, 78.77, 80.53, 81.84, 89.89, 89.58, 93.11, 88.4, 83.23, 82.28, 83.81, 84.16, 80.87, 77.15, 76.52, 77.81, 75.63, 76.04, 74.11, 72.01, 71.21, 69.54, 71.79, 72.32, 76.03, 74.6, 72.66, 73.76, 70.4, 69.03, 66.79, 67.66, 67.19, 67.97, 65.34, 65.32, 63.04, 64.37, 65.68, 64.91, 66.15, 64.15, 62.09, 61.15, 60.58, 60.43, 62.89, 61.99, 61.35, 62.41, 63.21, 62.33, 61.54, 58.48, 58.23, 55.52, 56.35, 55.43, 54.71, 54.11, 51.82, 47.88, 47.36, 47.94, 49.3, 52.81, 50.19, 45.86, 51.39, 50.89, 54.83, 59.38, 59.51, 63.55, 61.47, 62.55, 64.58, 63.92, 59.47, 58.09, 63.2, 67.58, 68.63, 70.37, 69.63, 64.03, 68.4, 75.47, 73.09, 72.46, 79.2, 80.64, 85.24, 80.11]
Vanguard Index Funds: Vanguard 500 Index Fund; Investor Shares | VFINX | [98.95, 100.68, 109.43, 107.73, 101.62, 98.57, 102.25, 100.3, 94.64, 96.44, 92.98, 89.75, 83.43, 83.24, 78.81, 71.94, 66.13, 74.02, 80.82, 79.96, 86.14, 103.53, 113.64, 112.02, 112.96, 123.39, 121.82, 116.17, 116.69, 120.61, 128.33, 129.23, 134.87, 132.78, 128.01, 126.12, 130.14, 132.36, 127.91, 122.5, 121.15, 123.58, 121.77, 120.08, 117.87, 114.16, 111.3, 108.74, 108.08, 107.94, 111.16, 109.7, 108.36, 108.08, 105.3, 105.27, 101.45, 103.18, 102.37, 103.31, 99.62, 99.5, 96.44, 98.32, 100.08, 98.03, 100.5, 97.2, 93.42, 92.03, 91.05, 90.71, 93.81, 92.04, 90.81, 92.26, 93.68, 92.41, 90.75, 86.25, 85.51, 80.94, 81.82, 80.27, 78.9, 77.91, 74.02, 68.37, 67.73, 68.77, 70.63, 75.25, 70.89, 65.17, 73.13, 72.65, 78.73, 84.79, 85.43, 90.96, 87.67, 89.41, 90.74, 89.95, 83.56, 82.01, 89.23, 95.2, 96.17, 98.58, 97.94, 90.88, 97.05, 106.81, 103.16, 102.63, 111.41, 111.89, 118.14, 111.25]
Vanguard STAR Funds: Vanguard STAR Fund; Investor Shares | VGSTX | [16.99, 17.35, 18.36, 18.14, 17.43, 17.14, 17.49, 17.29, 16.66, 16.88, 16.32, 15.92, 14.96, 14.84, 14.09, 13.17, 12.43, 13.26, 14.01, 13.42, 13.9, 15.97, 17.29, 17.25, 17.41, 18.34, 18.16, 17.52, 17.74, 17.99, 18.68, 18.88, 19.3, 18.93, 18.43, 18.3, 18.57, 18.7, 18.3, 17.81, 17.7, 17.71, 17.53, 17.4, 17.06, 16.68, 16.41, 16.06, 16.01, 16.02, 16.42, 16.23, 16.14, 16.14, 15.71, 15.46, 15.08, 15.35, 15.12, 15.02, 14.71, 14.58, 14.21, 14.33, 14.53, 14.32, 14.49, 14.08, 13.66, 13.47, 13.22, 13.11, 13.41, 13.19, 13.11, 13.44, 13.45, 13.25, 12.98, 12.57, 12.41, 11.97, 11.87, 11.65, 11.65, 11.54, 10.99, 10.39, 10.36, 10.45, 10.58, 10.81, 10.43, 10.08, 10.69, 10.51, 11.13, 11.65, 11.65, 11.87, 11.57, 11.6, 11.74, 11.55, 11.16, 10.93, 11.57, 11.84, 11.81, 11.98, 11.82, 11.34, 11.57, 11.95, 11.67, 11.15, 11.49, 11.45, 11.54, 10.97]
Vanguard World Funds: Vanguard International Growth Fund; Investor Shares | VWIGX | [15.3, 15.43, 17.22, 17.42, 16.25, 16.13, 16.99, 16.72, 16.03, 16.31, 15.47, 15.11, 13.68, 13.84, 12.13, 10.77, 9.89, 10.72, 12.0, 11.05, 11.99, 15.53, 17.83, 18.6, 19.36, 21.29, 20.84, 19.69, 19.88, 19.71, 21.66, 22.16, 22.92, 21.8, 20.5, 20.64, 20.97, 20.81, 20.16, 19.26, 18.79, 18.94, 18.72, 18.14, 17.62, 16.94, 16.96, 16.49, 16.31, 16.26, 17.07, 16.34, 15.83, 15.9, 14.86, 14.06, 13.74, 14.19, 13.59, 13.16, 12.71, 12.57, 12.56, 12.85, 13.17, 12.65, 12.92, 12.36, 11.6, 11.3, 11.0, 10.9, 11.28, 11.08, 11.12, 11.54, 11.39, 11.11, 10.86, 10.18, 10.0, 9.48, 9.31, 9.07, 8.8, 8.66, 8.2, 7.47, 7.55, 7.81, 8.08, 8.38, 7.97, 7.45, 8.46, 8.46, 9.41, 9.83, 9.91, 9.84, 9.35, 9.36, 9.79, 9.47, 9.01, 8.71, 9.86, 10.15, 10.38, 10.81, 11.21, 10.63, 11.34, 12.14, 12.08, 11.57, 11.85, 12.23, 13.07, 13.17]
Fidelity Select Portfolios: Computers Portfolio | FDCPX | [45.31, 45.96, 48.18, 46.41, 43.59, 41.23, 45.59, 42.11, 40.16, 41.95, 38.9, 36.9, 33.07, 31.23, 30.56, 26.86, 23.45, 24.95, 24.89, 25.21, 29.11, 34.94, 41.12, 40.34, 40.74, 45.73, 43.24, 39.64, 40.25, 39.32, 48.35, 48.19, 52.8, 47.69, 46.05, 44.38, 43.77, 43.23, 40.55, 39.63, 39.28, 40.72, 39.49, 39.59, 37.8, 36.39, 35.36, 32.32, 34.12, 35.39, 38.04, 37.67, 37.55, 37.78, 36.08, 36.36, 33.98, 35.54, 35.6, 36.06, 33.71, 34.31, 31.09, 33.4, 34.65, 33.34, 35.15, 34.02, 32.11, 29.74, 28.58, 30.75, 34.9, 34.65, 32.57, 36.16, 37.5, 37.97, 35.86, 36.61, 35.84, 31.91, 32.85, 30.28, 28.13, 28.0, 24.4, 22.08, 22.36, 21.54, 22.04, 25.8, 22.57, 19.06, 22.3, 23.16, 26.47, 30.78, 32.08, 35.69, 32.73, 38.11, 38.03, 37.28, 32.71, 27.22, 36.88, 41.36, 43.24, 42.03, 44.69, 36.57, 41.3, 59.26, 52.32, 53.81, 73.64, 79.99, 93.9, 80.52]
Fidelity Select Portfolios: Electronics Portfolio | FSELX | [39.71, 40.65, 43.6, 42.88, 39.66, 37.14, 41.5, 36.33, 34.49, 37.79, 36.66, 35.12, 30.09, 29.26, 27.84, 24.29, 20.92, 21.3, 22.43, 21.31, 25.36, 30.43, 36.9, 35.63, 37.71, 41.94, 39.66, 36.73, 36.46, 37.67, 44.73, 44.7, 48.84, 49.53, 48.38, 47.85, 48.25, 46.77, 46.46, 43.67, 45.0, 43.3, 42.74, 43.82, 42.01, 41.22, 41.33, 38.54, 40.94, 42.14, 46.55, 45.14, 45.41, 46.66, 42.61, 42.55, 38.13, 41.23, 40.95, 41.56, 38.17, 38.44, 34.74, 36.54, 37.93, 35.14, 36.81, 35.28, 34.25, 32.04, 30.41, 33.55, 39.22, 40.54, 37.23, 41.54, 42.55, 43.32, 40.82, 41.12, 39.48, 35.16, 36.66, 32.57, 30.05, 31.02, 26.88, 24.01, 24.26, 22.74, 23.75, 30.44, 24.4, 20.8, 26.1, 28.43, 33.24, 40.95, 43.55, 48.96, 43.14, 49.05, 48.01, 47.21, 40.41, 32.6, 47.12, 51.53, 52.1, 50.98, 54.88, 43.64, 47.02, 66.61, 56.3, 55.7, 75.43, 81.75, 102.1, 87.55]
Fidelity Select Portfolios: Telecommunications Portfolio | FSTCX | [37.91, 38.72, 40.02, 39.96, 37.73, 37.01, 40.03, 37.99, 35.42, 37.28, 34.94, 35.77, 34.22, 33.93, 32.4, 28.84, 26.49, 25.65, 26.41, 25.52, 25.11, 33.85, 40.14, 39.42, 39.53, 44.54, 43.53, 40.26, 41.38, 44.49, 50.44, 51.38, 55.76, 57.21, 54.27, 53.83, 55.1, 55.18, 50.64, 49.51, 48.85, 49.34, 46.6, 45.1, 45.02, 43.93, 42.09, 39.97, 40.36, 39.67, 41.91, 42.42, 40.2, 38.84, 37.12, 37.38, 35.56, 36.1, 35.64, 36.15, 34.35, 33.97, 32.11, 32.46, 33.08, 33.43, 35.31, 34.23, 32.52, 31.52, 30.37, 31.01, 31.4, 30.64, 30.91, 32.24, 33.59, 32.47, 30.07, 28.16, 28.23, 25.81, 26.98, 26.13, 27.29, 26.64, 24.16, 22.27, 22.13, 23.87, 23.96, 26.31, 22.19, 17.54, 20.13, 17.31, 20.14, 24.31, 24.65, 28.47, 28.6, 31.3, 33.9, 33.73, 31.65, 33.26, 34.64, 38.31, 38.47, 40.55, 41.47, 38.22, 42.93, 51.11, 47.07, 48.16, 59.06, 62.84, 72.49, 69.14]
Vanguard Fixed Income Securities Funds: Vanguard Long-Term Treasury Fund; Investor Shares | VUSTX | [11.6, 11.55, 11.12, 10.86, 11.03, 11.05, 10.76, 11.41, 11.19, 11.36, 11.14, 10.95, 10.87, 10.79, 11.08, 11.67, 11.08, 11.19, 12.23, 11.23, 10.02, 10.4, 10.37, 10.19, 10.16, 9.98, 10.19, 10.38, 10.28, 10.24, 9.98, 10.02, 9.58, 9.45, 9.43, 9.25, 9.03, 9.11, 9.29, 9.21, 9.32, 9.05, 9.13, 9.33, 9.15, 9.08, 8.94, 8.7, 8.55, 8.49, 8.49, 8.66, 8.96, 8.89, 8.97, 8.77, 8.72, 8.87, 9.12, 8.87, 9.1, 8.96, 8.73, 8.46, 8.52, 8.63, 8.41, 8.23, 8.42, 8.3, 8.22, 7.95, 7.83, 7.76, 7.8, 8.26, 8.14, 7.98, 7.85, 7.75, 7.73, 7.93, 7.55, 7.44, 8.14, 8.26, 7.82, 7.75, 7.84, 7.61, 7.64, 7.31, 7.41, 7.63, 7.33, 7.03, 6.83, 6.71, 6.69, 6.45, 6.71, 6.63, 6.55, 6.67, 7.02, 6.68, 6.62, 6.49, 6.26, 6.22, 6.2, 6.37, 6.41, 6.29, 6.27, 6.12, 5.94, 5.85, 5.9, 5.78]
Van Eck Funds: Emerging Markets Fund; Class A Shares | GBFAX | [10.09, 10.24, 11.3, 10.98, 10.21, 10.07, 10.65, 10.2, 9.7, 9.72, 8.96, 8.82, 7.77, 7.88, 6.14, 4.88, 4.3, 4.54, 4.82, 4.62, 5.21, 7.89, 10.46, 11.71, 12.39, 14.02, 13.55, 12.37, 13.47, 13.39, 15.19, 15.26, 16.21, 14.99, 13.89, 14.51, 14.04, 13.44, 12.52, 11.9, 11.44, 11.27, 11.2, 10.59, 9.75, 9.47, 9.34, 9.14, 8.93, 9.09, 9.97, 9.41, 9.1, 8.93, 8.05, 7.53, 7.13, 7.59, 6.92, 6.9, 6.59, 6.35, 6.4, 6.5, 6.79, 6.42, 6.21, 5.97, 5.44, 5.23, 4.92, 4.67, 4.76, 4.89, 5.02, 5.53, 5.62, 5.34, 5.18, 4.8, 4.7, 4.36, 4.21, 3.89, 3.6, 3.36, 3.06, 2.81, 2.9, 2.92, 2.96, 3.15, 3.05, 2.87, 3.23, 3.2, 3.47, 3.73, 3.76, 3.87, 3.68, 3.74, 3.95, 3.9, 3.64, 3.54, 3.98, 4.3, 4.49, 4.7, 4.79, 4.39, 4.9, 5.59, 5.48, 5.37, 6.01, 6.28, 6.8, 6.47]
Fidelity Investment Trust: Fidelity International Discovery Fund | FIGRX | [26.69, 26.91, 30.12, 30.6, 28.56, 28.65, 30.34, 29.62, 28.42, 29.24, 28.04, 27.07, 24.66, 25.08, 22.27, 20.16, 19.01, 20.78, 23.32, 21.76, 23.19, 29.12, 33.44, 35.33, 36.94, 39.75, 38.99, 37.05, 37.79, 37.69, 41.84, 42.33, 44.21, 41.59, 38.73, 39.13, 39.35, 39.25, 37.98, 36.28, 35.19, 35.41, 35.17, 33.93, 32.78, 31.62, 31.65, 30.82, 30.58, 30.82, 32.46, 31.08, 29.81, 30.4, 28.31, 26.68, 25.95, 26.82, 25.72, 24.89, 24.07, 23.54, 23.44, 23.77, 24.55, 23.54, 23.84, 22.72, 21.19, 20.4, 19.94, 19.87, 20.97, 20.48, 20.42, 21.05, 21.05, 20.61, 20.02, 18.61, 18.17, 17.13, 16.61, 15.94, 15.46, 15.0, 13.98, 12.87, 13.08, 13.51, 13.97, 14.2, 13.76, 13.26, 14.66, 14.7, 16.14, 16.72, 16.44, 16.14, 15.13, 14.93, 15.41, 15.22, 14.47, 13.84, 15.65, 15.92, 16.4, 17.02, 17.38, 16.23, 17.46, 18.85, 18.66, 18.26, 19.26, 19.98, 21.0, 20.18]
Fidelity Concord Street Trust: Spartan US Equity Index Fund; Investor Class Shares | FUSEX | [38.01, 38.67, 42.03, 41.55, 39.19, 38.01, 39.43, 38.68, 36.49, 37.19, 35.86, 34.61, 32.17, 32.11, 30.4, 27.75, 25.5, 28.55, 31.17, 30.84, 33.23, 39.93, 43.85, 43.22, 43.59, 47.61, 47.0, 44.82, 45.02, 46.53, 49.5, 49.85, 52.03, 51.22, 49.37, 48.64, 50.19, 51.05, 49.33, 47.23, 46.72, 47.66, 46.94, 46.3, 45.44, 44.01, 42.91, 41.91, 41.66, 41.61, 42.84, 42.27, 41.76, 41.65, 40.57, 40.56, 39.09, 39.75, 39.44, 39.79, 38.37, 38.32, 37.14, 37.86, 38.53, 37.75, 38.7, 37.42, 35.97, 35.28, 35.06, 34.92, 36.12, 35.43, 34.96, 35.52, 36.07, 35.58, 34.95, 33.21, 32.92, 31.16, 31.51, 30.91, 30.37, 30.0, 28.5, 26.33, 26.08, 26.48, 27.2, 28.98, 27.3, 25.09, 28.15, 27.97, 30.33, 32.76, 33.01, 35.14, 33.87, 34.53, 35.06, 34.75, 32.29, 31.68, 34.48, 36.79, 37.25, 38.09, 37.84, 35.12, 37.51, 41.27, 39.87, 39.68, 43.07, 43.26, 45.67, 43.0]
T Rowe Price Media & Telecommunications Fund, Inc | PRMTX | [42.94, 41.82, 44.87, 43.43, 40.17, 38.77, 41.03, 39.37, 36.36, 37.72, 34.16, 33.37, 30.5, 30.03, 28.35, 24.33, 22.32, 23.33, 24.35, 22.74, 25.51, 32.6, 38.18, 37.77, 38.22, 43.39, 42.16, 38.58, 39.26, 39.9, 45.53, 45.36, 48.49, 46.39, 43.57, 44.23, 43.64, 44.02, 40.7, 38.79, 38.24, 39.13, 37.33, 36.81, 35.21, 33.11, 31.76, 30.41, 31.25, 30.97, 32.86, 31.45, 30.43, 30.64, 29.04, 28.6, 27.09, 27.67, 27.05, 26.76, 25.29, 24.61, 23.24, 23.53, 23.95, 23.61, 24.58, 23.41, 21.91, 20.78, 19.66, 20.16, 21.47, 21.08, 20.28, 20.69, 20.71, 20.32, 19.46, 18.38, 17.91, 16.35, 16.53, 15.94, 15.45, 14.95, 13.66, 12.16, 12.03, 12.47, 12.4, 13.42, 11.95, 10.6, 11.45, 10.95, 11.82, 13.92, 13.96, 15.31, 14.84, 15.38, 17.18, 16.45, 15.5, 15.37, 16.13, 18.12, 18.47, 18.29, 18.93, 15.74, 18.03, 21.8, 18.46, 17.71, 21.84, 22.16, 24.87, 23.81]
Fidelity Investment Trust: Fidelity Emerging Markets Fund | FEMKX | [20.75, 21.05, 23.26, 23.09, 21.31, 21.29, 22.61, 21.75, 20.45, 20.78, 18.88, 18.9, 16.96, 17.17, 14.31, 12.44, 11.1, 11.74, 12.85, 11.99, 13.28, 19.5, 24.16, 26.6, 28.76, 31.87, 30.8, 28.41, 30.31, 28.65, 32.78, 32.45, 34.8, 30.77, 27.59, 28.37, 27.08, 26.08, 24.61, 23.43, 22.29, 22.38, 22.6, 21.68, 20.24, 19.2, 19.16, 18.67, 18.35, 18.52, 20.85, 19.39, 18.91, 19.17, 16.95, 15.74, 14.27, 15.16, 13.79, 13.53, 12.58, 12.19, 11.72, 12.05, 12.96, 11.87, 11.71, 11.01, 10.14, 9.88, 9.28, 8.89, 9.18, 9.3, 9.54, 10.47, 10.25, 9.85, 9.52, 8.8, 8.71, 8.09, 8.08, 7.56, 7.15, 6.83, 6.4, 5.92, 6.12, 6.35, 6.4, 6.51, 6.2, 5.91, 6.64, 6.58, 7.09, 7.63, 7.78, 7.7, 7.25, 7.14, 6.88, 6.39, 5.72, 5.44, 6.38, 6.52, 6.95, 7.09, 7.0, 6.63, 7.37, 7.9, 7.05, 6.9, 7.62, 8.18, 9.16, 9.06]
Fidelity Mt Vernon Street Trust: Fidelity Growth Strategies Fund | FDEGX | [16.33, 16.69, 18.18, 17.65, 16.35, 15.42, 16.27, 15.28, 14.34, 15.31, 14.53, 14.0, 13.04, 13.19, 12.55, 11.43, 10.37, 11.06, 11.65, 11.25, 12.35, 15.43, 17.81, 18.6, 19.6, 20.87, 19.74, 18.32, 19.37, 20.11, 22.96, 22.69, 25.04, 23.61, 22.24, 22.34, 22.01, 21.63, 20.83, 19.81, 19.79, 19.79, 19.33, 19.61, 18.52, 17.6, 17.3, 16.65, 17.27, 17.5, 18.86, 18.87, 18.46, 19.04, 17.75, 17.43, 16.79, 17.32, 17.18, 17.14, 16.24, 15.99, 14.94, 15.2, 15.59, 15.86, 16.51, 15.87, 15.25, 15.01, 14.47, 14.6, 15.98, 15.58, 15.25, 15.58, 15.58, 15.19, 14.85, 14.57, 14.24, 13.41, 13.61, 13.1, 12.73, 12.56, 11.7, 11.12, 10.91, 11.07, 11.13, 12.17, 10.62, 9.22, 10.67, 11.06, 11.94, 14.05, 15.06, 16.66, 15.87, 17.66, 18.92, 18.89, 17.07, 14.56, 18.46, 21.42, 24.41, 27.22, 28.13, 23.18, 29.35, 36.65, 35.89, 33.46, 43.41, 48.8, 53.81, 46.18]
Vanguard Fixed Income Securities Funds: Vanguard Intermediate-Term Treasury Fund; Investor Shares | VFITX | [11.62, 11.41, 11.2, 11.09, 11.19, 11.15, 10.93, 11.29, 11.07, 11.04, 10.94, 10.84, 10.78, 10.82, 10.94, 11.14, 10.79, 10.85, 11.12, 10.73, 10.16, 10.3, 10.25, 10.15, 10.07, 9.99, 10.12, 10.34, 10.25, 10.11, 9.81, 9.78, 9.45, 9.38, 9.33, 9.15, 8.99, 9.01, 9.11, 9.06, 9.06, 8.89, 8.92, 9.0, 8.9, 8.85, 8.77, 8.63, 8.52, 8.51, 8.51, 8.54, 8.62, 8.62, 8.64, 8.56, 8.52, 8.58, 8.68, 8.54, 8.66, 8.62, 8.51, 8.37, 8.41, 8.49, 8.45, 8.36, 8.49, 8.41, 8.4, 8.23, 8.15, 8.11, 8.15, 8.42, 8.33, 8.23, 8.17, 8.09, 8.1, 8.21, 7.96, 7.95, 8.27, 8.3, 8.08, 8.06, 8.08, 7.94, 7.97, 7.76, 7.88, 7.93, 7.7, 7.52, 7.32, 7.2, 7.12, 6.94, 7.11, 7.02, 6.98, 7.07, 7.23, 7.08, 6.91, 6.83, 6.66, 6.63, 6.62, 6.69, 6.66, 6.58, 6.49, 6.34, 6.21, 6.15, 6.1, 6.0]
Vanguard Index Funds: Vanguard Total Stock Market Index Fund; Investor Shares | VTSMX | [25.59, 27.25, 29.62, 28.99, 27.28, 26.39, 27.35, 26.59, 25.17, 25.84, 24.8, 23.92, 22.19, 22.11, 20.98, 18.97, 17.46, 19.5, 21.25, 20.87, 22.66, 27.5, 30.31, 29.84, 30.07, 32.76, 32.09, 30.55, 30.73, 31.7, 33.75, 33.96, 35.56, 34.91, 33.7, 33.22, 34.39, 34.97, 33.73, 32.43, 32.07, 32.6, 32.0, 31.64, 30.95, 29.89, 29.23, 28.57, 28.61, 28.56, 29.51, 29.19, 28.67, 28.67, 27.7, 27.67, 26.61, 27.11, 26.89, 27.14, 26.07, 25.86, 24.92, 25.51, 25.97, 25.44, 26.14, 25.22, 24.09, 23.7, 23.29, 23.22, 24.14, 23.64, 23.33, 23.83, 24.09, 23.75, 23.23, 22.24, 21.93, 20.67, 20.91, 20.42, 19.95, 19.67, 18.54, 17.13, 16.95, 17.24, 17.69, 18.78, 17.66, 16.4, 18.24, 18.15, 19.73, 21.23, 21.49, 22.6, 21.65, 22.1, 22.38, 21.99, 20.43, 19.93, 21.9, 23.3, 23.7, 24.1, 23.86, 22.05, 23.65, 26.1, 25.14, 24.71, 27.42, 27.99, 29.36, 27.37]
Vanguard Valley Forge Funds: Vanguard Balanced Index Fund; Investor Shares | VBINX | [18.87, 19.51, 20.43, 20.08, 19.36, 18.96, 19.25, 19.05, 18.34, 18.59, 18.05, 17.59, 16.7, 16.62, 16.04, 15.08, 14.21, 15.2, 16.03, 15.64, 16.2, 18.33, 19.5, 19.26, 19.35, 20.36, 20.16, 19.6, 19.65, 20.0, 20.6, 20.67, 21.08, 20.77, 20.27, 19.99, 20.34, 20.57, 20.19, 19.68, 19.55, 19.62, 19.41, 19.32, 18.97, 18.52, 18.22, 17.86, 17.77, 17.74, 18.1, 18.0, 17.88, 17.85, 17.48, 17.4, 16.96, 17.22, 17.2, 17.21, 16.86, 16.74, 16.29, 16.43, 16.64, 16.48, 16.7, 16.28, 15.88, 15.68, 15.5, 15.34, 15.65, 15.42, 15.32, 15.68, 15.74, 15.54, 15.28, 14.83, 14.69, 14.23, 14.17, 13.94, 13.93, 13.81, 13.24, 12.58, 12.51, 12.56, 12.75, 13.09, 12.63, 12.12, 12.81, 12.69, 13.25, 13.8, 13.86, 14.18, 13.91, 14.03, 14.09, 13.97, 13.47, 13.18, 13.84, 14.28, 14.3, 14.41, 14.29, 13.66, 14.17, 14.97, 14.53, 14.27, 15.08, 15.22, 15.61, 14.88]
Vanguard Index Funds: Vanguard Growth Index Fund; Investor Shares | VIGRX | [27.33, 26.62, 29.02, 28.58, 26.99, 26.01, 27.26, 26.37, 24.92, 25.27, 24.17, 23.71, 22.14, 21.83, 20.91, 19.15, 17.68, 19.08, 20.0, 19.77, 21.62, 26.27, 29.67, 29.32, 29.87, 32.02, 30.89, 29.19, 29.43, 29.85, 32.43, 32.37, 33.49, 32.44, 31.11, 30.6, 31.09, 31.47, 30.42, 29.15, 28.99, 29.58, 28.81, 28.77, 28.15, 27.22, 26.46, 25.69, 26.22, 26.32, 27.29, 27.3, 26.91, 27.08, 26.43, 26.54, 25.44, 25.66, 25.58, 25.91, 24.77, 24.81, 23.67, 24.25, 24.66, 24.38, 25.15, 24.24, 23.34, 22.99, 22.68, 22.83, 24.16, 23.9, 23.45, 23.81, 24.19, 23.98, 23.46, 22.78, 22.58, 21.26, 21.63, 21.14, 20.6, 20.35, 19.71, 18.46, 18.1, 18.15, 18.63, 20.02, 19.0, 17.4, 19.42, 19.3, 20.26, 22.02, 22.47, 24.2, 23.65, 24.37, 24.4, 24.38, 22.39, 21.61, 23.17, 24.84, 24.91, 25.26, 25.2, 23.14, 25.44, 28.84, 28.04, 29.35, 32.85, 33.73, 37.39, 35.35]
Vanguard International Equity Index Funds: Emerging Markets Stock Index Fund; Investor Shares | VEIEX | [24.12, 24.13, 26.61, 26.54, 24.54, 24.28, 25.91, 25.0, 23.61, 23.93, 21.9, 22.03, 19.75, 20.2, 17.1, 14.73, 12.69, 13.51, 14.72, 13.6, 14.76, 20.41, 24.36, 26.42, 27.57, 30.75, 30.21, 27.95, 29.05, 27.76, 31.22, 31.32, 34.04, 30.31, 27.37, 27.64, 26.49, 25.35, 23.93, 22.95, 22.05, 22.33, 22.46, 21.57, 20.07, 19.16, 19.02, 18.64, 18.43, 18.46, 20.68, 19.3, 19.07, 19.35, 17.36, 16.35, 15.14, 16.21, 14.92, 14.78, 13.83, 13.39, 12.95, 13.33, 14.29, 13.13, 13.15, 12.48, 11.33, 11.07, 10.48, 10.07, 10.26, 10.26, 10.35, 11.24, 11.2, 10.75, 10.42, 9.67, 9.57, 8.77, 8.7, 8.18, 7.64, 7.22, 6.78, 6.24, 6.37, 6.62, 6.61, 6.79, 6.38, 5.99, 6.71, 6.61, 7.23, 7.87, 7.91, 7.88, 7.54, 7.35, 7.14, 6.63, 6.06, 5.69, 6.73, 6.8, 7.29, 7.46, 7.34, 6.72, 7.5, 8.21, 7.35, 6.93, 7.69, 8.33, 8.88, 8.74]
Vanguard STAR Funds: Vanguard Total International Stock Index Fund; Investor Shares | VGTSX | [12.68, 12.83, 14.38, 14.63, 13.71, 13.68, 14.41, 14.19, 13.68, 13.97, 13.27, 12.84, 11.67, 11.83, 10.34, 9.17, 8.39, 9.28, 10.54, 9.74, 10.39, 13.34, 15.35, 16.17, 16.79, 18.45, 18.17, 17.17, 17.29, 17.23, 18.84, 19.29, 20.21, 19.08, 17.94, 18.07, 18.26, 18.15, 17.61, 16.94, 16.48, 16.47, 16.31, 15.82, 15.26, 14.67, 14.63, 14.27, 14.11, 14.16, 14.82, 14.1, 13.67, 13.77, 12.88, 12.25, 11.93, 12.35, 11.79, 11.47, 11.06, 10.92, 10.91, 11.14, 11.47, 10.96, 11.15, 10.67, 9.95, 9.64, 9.36, 9.29, 9.62, 9.39, 9.35, 9.65, 9.61, 9.37, 9.23, 8.56, 8.38, 7.87, 7.65, 7.47, 7.24, 7.05, 6.64, 6.05, 6.17, 6.29, 6.5, 6.67, 6.39, 6.04, 6.78, 6.79, 7.53, 7.87, 7.78, 7.74, 7.32, 7.26, 7.61, 7.51, 7.25, 7.04, 7.89, 8.07, 8.27, 8.6, 8.92, 8.27, 8.9, 9.64, 9.53, 9.19, 9.62, 9.92, 10.44, 10.34]
Schwab Capital Trust: Schwab Small-Cap Index Fund; Select Shares | SWSSX | [18.07, 18.0, 19.51, 18.42, 16.96, 16.26, 16.78, 15.53, 15.0, 16.01, 15.1, 14.53, 13.19, 13.04, 12.56, 10.5, 9.59, 11.0, 12.37, 11.75, 13.39, 16.9, 18.4, 17.65, 17.19, 19.04, 18.27, 17.37, 17.36, 17.88, 19.02, 19.24, 20.56, 20.03, 19.76, 19.41, 20.68, 21.0, 20.13, 19.7, 19.42, 19.48, 19.03, 21.44, 20.84, 19.74, 19.53, 19.08, 19.7, 19.67, 20.68, 20.6, 19.77, 19.88, 18.4, 18.52, 17.7, 18.25, 18.17, 18.52, 17.45, 16.88, 15.78, 16.72, 17.21, 16.88, 17.55, 17.03, 15.68, 15.37, 14.61, 14.72, 15.77, 15.07, 14.82, 15.6, 15.54, 15.48, 15.05, 14.84, 14.34, 13.24, 13.52, 12.89, 12.25, 12.03, 10.87, 9.84, 9.72, 10.05, 10.56, 11.34, 10.43, 10.15, 10.86, 10.8, 12.51, 13.2, 13.83, 13.9, 12.79, 13.26, 13.75, 13.5, 12.57, 11.96, 13.93, 14.33, 15.0, 14.36, 13.99, 12.95, 13.56, 14.67, 14.43, 14.99, 16.57, 16.86, 17.38, 15.8]
Vanguard Specialized Funds: Vanguard REIT Index Fund; Investor Shares | VGSIX | [15.42, 16.42, 17.36, 16.22, 14.72, 13.95, 14.73, 13.76, 12.88, 13.51, 12.67, 11.11, 10.04, 10.38, 10.14, 7.72, 7.46, 9.41, 11.39, 9.7, 12.67, 18.42, 18.44, 18.03, 17.48, 19.6, 19.57, 18.48, 17.36, 18.03, 18.1, 19.07, 21.02, 20.77, 19.92, 18.71, 20.29, 22.36, 22.38, 22.39, 22.94, 23.5, 21.66, 22.06, 21.07, 19.86, 19.49, 18.79, 18.16, 17.24, 17.74, 18.41, 17.56, 17.24, 16.04, 16.05, 15.4, 15.77, 15.68, 16.29, 15.23, 14.51, 14.05, 13.28, 13.49, 13.12, 14.33, 13.67, 13.13, 12.45, 12.48, 11.58, 11.52, 11.2, 10.46, 12.24, 11.62, 11.43, 10.96, 10.63, 10.19, 10.03, 9.7, 9.64, 9.16, 8.96, 8.49, 8.16, 8.0, 7.86, 8.08, 8.02, 7.67, 8.07, 8.37, 8.35, 8.82, 8.58, 8.47, 8.42, 7.92, 7.77, 7.79, 7.6, 7.18, 7.44, 7.74, 7.47, 7.63, 7.21, 7.06, 6.9, 6.84, 6.96, 6.93, 6.49, 6.38, 6.69, 6.49, 6.76]
What does IDL stands for ?
What is IDL?
a.) International Document Language - a language-independent text format for transmitting documents
b.) Independent Device Layer - a software abstraction that sits on top of different hardware presenting a uniform interface
c.) Interface Definition Language - a programming-language-independent method for defining object interfaces
d.) Internet Dialup Layer - a communications layer that manages TCP/IP connections over a modem link
e.) Image Definition Language - a graphics definition language for defining portable images
Connection cn;
String queryStr;
// .. Code to open the connection and create a query not shown
cn.setAutoCommit(false);
cn.executeQuery(queryStr);
// *** Line A
In the code above, which one of the following substitutions for Line A writes the query results to the database?
a.) cn.update();
b.) cn.flush()
c.) cn.executeQuery("TRANSACTION END");
d.) cn.commit();
e.) cn.rollback();
FilePermission fp=new FilePermission("/tmp/110115.tmp","write");
AccessController.checkPermission(fp);
What happens if the code above is run from a thread that has NOT been granted access to the /tmp directory?
a.) The runtime system presents a browser dialog to the user.
b.) The virtual machine exits.
c.) The call to AccessController throws an AccessControlException.
d.) The runtime system terminates the thread that called AccessController.
e.) The call to AccessController returns false.
BufferedImage im=
new BufferedImage(100,200,BufferedImage.TYPE_INT_RGB));
Graphics2D gc= im.createGraphics();
Where is the origin (0,0) of the image created above?
a.) In the center of the image
b.) In the top left corner
c.) In the top right corner
d.) In the bottom left corner
e.) In the depends on the AffineTransform in effect
What is the main purpose of Java servlets?
a.) They allow browsers to upload intelligent search agents to a Web server.
b.) They allow resource-limited devices such as printers or embedded systems to respond to http requests.
c.) They allow Java programs to access back-end databases such as Oracle and Sybase.
d.) They allow for generation of dynamic content and processing of user input on the Web.
e.) They handle the communications protocols required to send applets to Web browsers.
Which statement below describes a class that implements the Enumeration interface?
a.) It has implementations of the toString() and getNextString() methods.
b.) It is a subclass of Vector.
c.) It contains implementations of the hasMoreElements() and nextElement() methods.
d.) It can be used to store associative arrays.
e.) It can work with the StringTokenizer class.
How do you get a reference to the system clipboard?
a.) java.awt.Toolkit.getDefaultToolkit().getSystemClipboard()
b.) Java can't get access to the clipboard.
c.) new java.awt.datatransfer.Clipboard()
d.) System.lang.ClipBoard
e.) java.awt.datatransfer.Clipboard.getDesktopClipboard()
What is an RMI "stub"?
a.) It is used by the client to find remote objects on a server.
b.) It acts as a client-side proxy to receive RMI calls and pass them to the server.
c.) It enables applets to make RMI calls without violating browser security.
d.) It receives RMI calls from the server to enable applet callbacks.
e.) It is the interface implemented by both the client and server objects.
Which one of the following correctly describes the function of a bean's home interface in EJBs?
a.) It maps Java types to underlying database types.
b.) It defines how to create, find, or remove the bean.
c.) It defines all of the beans public methods.
d.) It is the container for the bean and it manages transactions.
e.) It interfaces to a naming service to allow remote objects to lookup the bean.
Which interface is intended to supersede Enumeration in the collections framework?
What happens if a parameter is passed to a remote object (using RMI) that does NOT implement Remote or Serializable?
class SuperClass {
private void printIt() {System.out.println("SuperClass");}
void printIt(boolean f) {
if (f) {
System.out.println("Super-part 2");
} else {
printIt();
}
}
}
class SubClass extends SuperClass {
void printIt() {System.out.println("SubClass");}
}
public class TestSub {
static void main(String args[]) {
SubClass sc=new SubClass();
sc.printIt();
sc.printIt(false);
}
}
How can you store a copy of an object at the same time other threads may be changing the object's properties?
// *** Line A
package com.brainbench.TestExamples;
// *** Line B
import java.io.*;
// *** Line C
public class DocumentationSample
// *** Line D
implements Serializable {
// *** Line E
// .. Code not shown ..
}
In the code sample above, where must you place a documentation comment that describes the purpose of the class DocumentationSample?
public class ArrayTest{
public static void main(String[] args){
// insert code here
}
}
Given the above sample code, what do you insert to print out a list of the command-line arguments?
a.) for(int i=0; i<args.getLength(); i++)
System.out.println(args[i]);
b.) for(int i=0; i<args.size(); i++)
System.out.println(args[i]);
c.) for(int i=0; i<args.length(); i++)
System.out.println(args[i]);
d.) for(int i=0; i<args.length; i++)
System.out.println(args[i]);
e.) for(int i=0; i<sizeof(args); i++)
System.out.println(args[i]);
<%@ page language="java" import="java.io.*" %>
<HTML>
<BODY>
The browser's IP address was:
<%-- *** Line A *** --%>
</BODY>
</HTML>
When substituted for Line A in the JSP code above, which one of the following lines displays the browser's IP address?
a.) <%= session.getRemoteAddr() %>
b.) <%= request.getRemoteAddr() %>
c.) <%= application.getRemoteAddr() %>
d.) <%= page.getRemoteAddr() %>
e.) <%= response.getRemoteAddr() %>
public double SquareRoot( double value ) throws ArithmeticException
{
if (value >= 0) return Math.sqrt( value );
else throw new ArithmeticException();
}
public double func(int x) {
double y = (double) x;
y *= -9.0;
try {
y = SquareRoot( y );
}
catch(ArithmeticException e) { y /= 3; }
finally { y += 10; }
return y;
}
Referring to the above, what value is returned when method func(9) is invoked?
char ch1 = 0,ch2 = 0;
try { ch1 = (char) System.in.read(); }
catch(Exception e) {}
switch(ch1) {
case 'a':
ch2 = '1';
case 'b':
ch2 = '2';
case 'c':
ch2 = '3';
default:
ch2 = '4';
}In reference to the above, if during execution the user presses "b," what is the ending value of "ch2"?
class A {
int i = 5;
public static void main(String args[]) {
A h = new A();
h.doIt();
}
void doIt() {
i += 1;
}
}
In reference to the above, what is special about the method main()?
public class SaveObject{
public static void main( String[] args ){
Employee smith = new Employee("012345","Smith","James","Payroll");
FileOutputStream fos = new FileOutputStream("smith.dat");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(smith);
fos.close();
}
}
Given the above sample code, which one of the following prevents the code from working properly?
public class SortSample {
public void printSorted(int arrayToSort[]) {
.. // Insert code to sort the array here
System.out.print("Sorted array is ");
for (int j=0; j<arrayToSort.length;j++)
System.out.print(arrayToSort[j]+" ");
System.out.println();
}
In the above code, what is the code-efficient way to sort the array into ascending order?
public class CashHolder {
private double amountHeld=0.0;
}
public void getCash() {
CashHolder wallet = new CashHolder();
// Lookup the Teller using RMI
Teller teller= (Teller) java.rmi.
Naming.lookup("//localhost/TellerObject");
// Withdraw 100.00 from account #9856432 and put it into
// Wallet.
teller.withdrawFunds("9856432",wallet,100.00);
// Go somewhere and spend it
..
}
How do you change the code above to allow teller.withdrawFunds() to update the CashHolder object passed to it?
Write a unit test for the fibonacci function above?
A)
long fib_A(unsigned long n) {
if (n <= 1) {
return n;
} else {
return fib_A(n-1) + fib_A(n-2);
}
}
B)
long fib_B(unsigned long n) {
int previous = -1;
int result = 1;
for (int i = 0; i <= n; i++)
{
int sum = result + previous;
previous = result;
result = sum;
}
return result;
What is the execution time (in Big O notation)
A)
long fib_A(unsigned long n) {
if (n <= 1) {
return n;
} else {
return fib_A(n-1) + fib_A(n-2);
}
}
B)
long fib_B(unsigned long n) {
int previous = -1;
int result = 1;
for (int i = 0; i <= n; i++)
{
int sum = result + previous;
previous = result;
result = sum;
}
return res
Which is more CPU Intensive?
In mapreduce, which type of join is more efficient, map side join or reduce side join and why?
Write in your most comfortable language) code that prints the numbers from 1 to 1 million.
But for multiples of prime number seven print "Multi" instead of the number and
for the multiples of prime number thirteen print "Attribution".
For numbers which are multiples of both three and five print "Multi-Attribution".
Given an array of size n, find all the possible sub set of the array of size k(all the subsets must be of size k).
Ad Center SDET interview always asks
Regular expression problems
Implement a lexical analyzer
Input string - a C program with Comments
Output- the input C program string without comments
How are events handled in COM ?
SCVMM - Or Server tools -SDET position
Test the find /replace dialog
Find the element closest to a given input element in a BST
key pad question - you how your phone has letters on the number keys. for example, number 2 has ABC on it, number 3 has DEF, 4 number has GHI,... , and number 9 has WXYZ. Write a program that will print out all of the possible combination of those letters depending on the users input. For example, say a user presses 234, the output should be
ADG, ADH, ADI, AEG, AEH, AEI, AFG, AFH, AFI
BDG, BDH, BDI, BEG, BEH, BEI, BFG, BFH, BFI
CDG, CDH, CDI, CEG, CEH, CEI, CFG, CFH, CFI
you are to write a program that figures out the total cost of an airline ticket. The base-fare is $40, tax rate is 4%, a customer is charged $10 per segment but only a maximum of 2 segments will ever be charge, and $10 per security screens but only a maximum of 3 security segments will ever be charged. Something like that, simple linear programming.
you are to write a program that simulates a cash register. for example, if something cost $10.25 and the customer pays with a $20 bill, the program will print out the most efficient "change-breakdown" which is 1 five, 4 ones, and 3 quarters.
you have to create a program that accepts a stream of inputs from a user and when the user enters 0, the user has signal the end of their inputs. From the stream of input, find the max and min, however the max must be an even number and the min must be an odd number.
reverse the words of a string. i.e This is great -> great is This
1. when would you prefer to use a linked list over an array and vice versa
2. given a binary tree, find the path from the root to all nodes whose id are multiples of five.
3. what data structures will you use if you have a program that accepts a stream of inputs and just stores those inputs
4. what is abstraction
5. how would you remove duplicates
Let us assume that we store integers in strings. Right an increment function in C that will increment a given integer by one.
Written Round1: Given two sorted arrays a[] and b[]. Merge them and answer should be stored in a[] with minimum complexity
Written Round1: To get mirror image of a binary tree.
There are a row of houses, each house can be painted with three colors red, blue and green. The cost of painting each house with a certain color is different. You have to paint all the houses such that no two adjacent houses have the same color. You have to paint the houses with minimum cost. How would you do it?
Note: Painting house-1 with red costs different from painting house-2 with red. The costs are different for each house and each color.
You are given a document having lot of words in it and many words have been used it the document more than once ... you are supposed to find each word with their occurrences in the document means its count .... assume you have been given a function char * GetNextWord() which fetches you next word from the document ....
1) propose the best data structure u will use to tackle this problem.
2) Write an algo to implement this
3) Tell the complexity
you are given a linked list and you are supposed to take it as input and return its node values as an integer ---
for example
if linked list it 2->3->4->5->NULL
it should return 2345 integer use functions definition as ---
int myconvert(Node *);
and structure for Node is
struct Node{
int data;
struct Node *root;
};
2) now you are given num1: 2->3->4->NULL;
and num2: 3->4->NULL;
you should take two linked list as input and return a list like 2->6->8->NULL; sum of corresponding elements and return a list
Node * newlist(Node *num1,Node *num2);
3) Write test cases to test 2nd program completely...
Find the output of the following code -
int find(int j)
{
if(j>1)
{
j=find(j/10)-(j%10);
printf("%d",j);
}
else
{
j=0;
}
return j;
}
int main()
{
int i=19222;
int k;
k=find(i);
}
fill all the numbers from 1 to 8 in the diagram shown below such that no two consecutive numbers are next to each other(either horizontally vertically or diagonally) i hope i am clear .. i mean 1 can not have a neighbor as 2 , 5 can't have neighbor as 6 or 4 ...
-----
| |
-------------------
| | | |
-------------------
| | | |
-------------------
| |
-------These question were asked in Written test held in delhi...
1) find the bug in the following code which concatenates 2 strings ---
char * concatenate(char *s1,char *s2)
{
char buffer[1024];
int i=0;
while(*s1)
{
buffer[i++]=*s1;
s1++;
}
while(*s2)
{
buffer[++i]=s2;
s2++;
}
return buffer;
}
These question were asked in Written test held in delhi...
1) find the bug in the following code which concatenates 2 strings ---
char * concatenate(char *s1,char *s2)
{
char buffer[1024];
int i=0;
while(*s1)
{
buffer[i++]=*s1;
s1++;
}
while(*s2)
{
buffer[++i]=s2;
s2++;
}
return buffer;
}
what does following program do?
int main(main)
{
printf("%d",main);
return 0;
}
How do you implement abstraction and encapsulation? Explain with example.
Given a triangle like the following
3
4 6
1 5 01. How many nodes would you have, for 20 rows?
2. How to find the largest sum from the top of the triangle to the one of the nodes at the bottom. In other words, if you consider it as a tree, find the max sum of all paths from root to the leaf.
write down the output...even after knowing , i did wrong...:P u guys be careful..:P
int b=3;
cout<<b++*++b<<endl;Q. If you are given 2 number U & V then Write a program to find the GCD of the numbers. complexity of the program shoud be of the order {(log MN)^2 }.
Phone screen for a software developer role in wireless:
1) What is Fourier Transorm?
2)What is Capacitor
3)What is Nyquist frequency ?
4) what is CDMA FDMA TDMA
1. Given an array of strings, we have to write a function called reverseStringSort which have to reverse the given strings, sort it and again reverse it finally before displaying it.
write a function equivalent to the c function strstr(char* small, char* big) which is basically a method that returns the index of the first occurrence of the substring.
for example:
Small = "cat"
Big = "Application"
the function will return 5 because that is the index value where the substring first occurs
merge 2 sorted linked list into another sorted linked list, then do it in O(N) time and O(1) space
you have a Log file that stores the "users id", "time"(irrelevant), and "webpage visited." Find the most common three-sequence webpage visited by the users. For example, you have a log file
joe, 12:30pm,home
joe, 12:31pm,about
joe, 12:32pm,career
james, 12:35pm, home
james, 12:36pm, cart
james, 12:37pm, maps
mary, 12:41pm, home
mary, 12:42pm, about
mary, 12:43pm, career
thus the most common sequence is home->about->career because the sequence occurs twice as oppose to home->car->maps which only occurs once.
In addition, this file is a huge file with many more entries.
write code to remove duplicates in O(N) time.
what data structures will you use if you have a program that accepts a stream of inputs and just stores those inputs. write the code also.
when would you prefer to use a linked list over an array and vice versa
given a binary tree, find the path from the root to all nodes whose id are multiples of five.
The best data structure to store the phone book.
Refer : http://en.wikipedia.org/wiki/Trie
Write a program to check the binary representation of an integer is palindrome or not ?
eg:
4 --To Binary--> 0100 : Not palindrome
6 --To Binary--> 0110 : Palindrome
How will you find n most frequently occurring patterns in a text file. What data structures would you use?
Here, a pattern is not a single word but rather a sequence of words. For instance, "this is a" could be a frequently occurring pattern in the file.
Followup questions:
- What if the file is very large (in GBs)?
- What if the file contains text in multiple languages (english, japanese etc)?
Give two binary search trees, print the numbers of both together in ascending order.
Add two big numbers represented as link lists without reversing the link lists.
How to find a first non repeating character in a String ?
What is the time to get min element from the binary max heap !!
o(n)
o(logn)
o(log log n))
o(1)
Round2: Q2
Given a array find the sub array with maximum sum.
Round2: Q1
There is a matrix where the cost of moving horizontally is 1, vertically is 1 and diagonally is 1.1. Now given two points, what is the number of shortest paths between these two points.
Hint: This will boil down to permutation with duplicates. Then he asked to code for this.
Round1: Q2
Discussion on various data structure where the following operations could have minimal cost:
1.insert
2.delete
3.search
4.return any element
Round1: Q1
Find the vertical sum in a binary tree.
Input:
(Plz construct the tree using the pre-order and in-order traversals)
Pre-order: 1 2 4 5 3 6 7
In-order: 4 2 5 1 6 3 7
Output:
Arr-Index Sum
0 4
1 2
3 12
4 3
5 7
Round 5: Q2:
Design an algorithm to find the immediate greater number to a given number, such that the result has the same digits as the given input number.
Example:
Input Output
1234 1243
1243 1324
Hint: Next Permutation of the given number
Round 5: Q1:
Write a function that takes an integer and returns a char array that contains the -2 base representation of the given integer.
Example:
Input Output
7 11011
3 111
2 110
Round 4:
Question on object-oriented design. (was asked to design MS-Paint application)
Other basic concepts of OOPS, Networks, Operating Systems, C programming.
Round 3:
General Discussion about the current work & work-culture.
Round 2: Q2:
Given a tree, in addition to the left and right pointer, it has a third pointer, that is set to NULL.
Set the third pointer to a node, which will be the successor of the current node, when the tree is traversed in the zig-zag order. In other words, if we traverse the tree using this third pointer alone, then we will be traversing the tree in the zig-zag order.
Input:
(Plz construct the tree using the pre-order and in-order traversals)
Pre-order: 1 2 4 5 3 6 7
In-order: 4 2 5 1 6 3 7
So, after the pointer is fixed, the traversal of the tree using the third pointer should give,
1 3 2 4 5 6 7
Round 2: Q1:
Given 2 unsorted arrays, find the intersection of the two arrays (optimal soln).
He was asking for various approaches and complexity in all those approaches.
Finally, he was interested in the solution using array-sorting.
Round 2: Discussion
Discussion on various data structures and search complexity in them.
Few questions on hashing.
Round 1: Q2:
Puzzle
Given 25 horses, find the best 3 horses with minimum number of races. Each race can have only 5 horses. You don't have a timer.
Round 1: Q1:
Given a matrix, print it spirally.
Input:
1 2 3
4 5 6
7 8 9
Output: 1 2 3 6 9 8 7 4 5
Written: Q3:
Given a string, compress using run-length encoding.
Example:
Input: aaabbac
Output: a3b2ac
Written: Q2:
Given a rotated-sorted array find the point of rotation. Complexity less than O(n).
Example:
Index: 0 1 2 3 4
Value: 4 5 1 2 3
Ans: 2 (index)
Written: Q1:
Given a binary search tree and a value X, find the node with value immediately greater than X.
Where should one start when attempting to learn Algorithms and Data Structures ? Books ?
Write two algorithms to remove duplicates from an integer array.
Discuss pros and cons.
Write test methods for your algorithms.
what are threads and processes. what is the meaning of synchronization
given a large chunk of memory. implement your own malloc and free function
how to find out if a point lies inside a triangle or not??
Design an Evaluation of a mathematical expression.
test a page with just a textbox and a search button.
Write the code to find the intersection of two arrays.
What is the probability of a knight staying on a chess board after K hops (input : starting position and K)
Given two dies, modify one such that you get the numbers 1 to 12 in equal
probability
Given 2*n + 3 points in 2d space, with no 3 points collinear and no 4 points lying on a circle, device an algorithm that will find a circle that contains n points inside it, n outside it and 3 on it.
Given an array of positive integers that represent the bars in a histogram,
find the rectangle with the largest area under the curve and above the axis.
Implement BFS on a tree using an iterative stack or recursively?
Question from Sony USA:
Without use of other function calls, rewrite this code to
ensure the pointer p is aligned to a 16-byte boundary for
its lifetime:
char *p = malloc(1024);
...
free(p);
given i/p: 4*4 matrix. find the distance between 2 points. provide all possible ways to reach to the other number
design an algorithm for returning the first repeated character in string
{sort a doubly link list in less then lg(n)n time??}
given an array of integers and a unique number. find all different combination of numbers from the array that add up to the unique number.print all the combination.
find all the permutations of a string.
Implement Game of Snake DS, Why this DS, Approaches for optimizing the current DS
How do efficiently search for a number in matrix given rows and columns are in increasing order.
Implement Alternative node swap of linked lists.
How do you efficiently implement suggest functionality in phone book. Suggest is like You will retrieve names as you type. Define the structure for it.
Given a binary tree ,Find the minimum sum from root to the leaf and also the path???
Given two nodes of tree .Find their first common ancestor???
k distinct integers [0, N)
Select a random no [0,N) which is not in this k distinct list.
Example:
[4, 6, 9]
Choose a random no between 0 - 9 which is not 4, or 6, or 9.
Valid output: 2
Invalid output: 6
how to find the first node(nearest to root) in the linked list which is in a loop.
search a number in a sorted array of the form
eg: 4 5 6 1 2 3
in O(logn).
int x=10;
x++++;
print x;
what is the result?
Drawbacks of using mutexes in threads.
Given an array 1 to N , how many permutations of it will be Min -Heap of of N! possible permutations
2-d array sorted both row wise and column wise. Find the search element - (logn complexity)
F2F Round 4: Design a hangman game web application.
F2F round 2: Given a long text, print the formatted text such that each line has atmost L characters and the text is left-right justified. No breaking of words are allowed.
F2F round 1: Edit distance dynamic programming question
Sort 100 million 10-bit integer in O(N) time.
sort three numbers without inserting them onto array(dont use stl container) ? What about 4 numbers?
what is virtual overloading?
use of arrays?
advantages and need of data mining?
Implement stack with min operation
Convert a BST to sorted Double linked list
Design Elevator Control system
Find where the cycle starts in P shaped Linked List
Implement pow function optimally
Why Finally block are used in java?
In C language "Call by value & Call by reference" have occured But do Java support "call by value Call by reference?
What is Enum?Why is the use of it?
there is a pyramid with 1 cup at level , 2 at level 2 , 3 at level 3 and so on..
It looks something like this
1
2 3
4 5 6
every cup has capacity C. you pour L liters of water from top . when cup 1 gets filled , it overflows to cup 2,3 equally, and when they get filled , Cup 4 and 6 get water only from 2 and 3 resp but 5 gets water from both the cups and so on.
Now given C and M .Find the amount of water in ith cup.
Consider the problem of neatly printing a paragraph on a printer. The input
text is a sequence of n words of lengths l1, l2, . . . , ln, measured in
characters. We want to print this paragraph neatly on a number of lines that
hold a maximum of M characters each. Our criterion of “neatness” is as
follows. If a given line contains words i through j, where i ≤ j , and we
leave exactly one space between words, the number of extra space characters
at the end of the line is M − j +i − Sum(lk)(from k = i to j) , which must
be nonnegative so that the words fit on the line. We wish to minimize the
sum, over all lines except the last, of the cubes of the numbers of extra
space characters at the ends of lines. Give a dynamic-programming algorithm
to print a paragraph of n words neatly on a printer. Analyze the running
time and space requirements of your algorithm.
Why do we prefer to sort the smaller partition of a file and push the larger one on stack after partitioning for quicksort(non-recursive implementation)? Doing this reduces the space complexity of quicksort O(log n) for random files. Could someone elaborate it?
Select the option that represents the definition of network database model.
Attempts to bring closer interactivity between database administrators and application programmers
Represents the entire information content of the database in only one way
Organizes the data in the form of a tree of records, with each record having one parent record and many children records
Allows each record to have multiple parent and child records, thereby forming a lattice structure
Which one of the following is NOT a referential integrity issue in a relational database where the DEPT column of the EMPLOYEE table is designated as a foreign key into the DEPARTMENT table?
Updating the value of DEPT in a row of EMPLOYEE with a value that is not the primary key of any of the rows in DEPARTMENT
Inserting a new row into DEPARTMENT with a primary key that is not the value of the DEPT column of any row in EMPLOYEE
Deleting a row of DEPARTMENT
Inserting a new row into EMPLOYEE with a DEPT whose value is not the primary key of any of the rows in DEPARTMENT
An organization stores its employee records in a table, “Emp”. This table has various attributes such as First Name, Last Name, Designation and Salary. The organization stores details of the employee's children in another table, “EmpChildren”. The EmpChildren table has attributes like First Name, Last Name, and Birth Date. The Emp table is a parent table and EmpChildren table is a child table. An employee may have many children, but each child will have only one parent.
From the following options, select the type of database model depicted by the above scenario.
Relational model
Network model
Hierarchical model
Object database mode
Implement a stack that pops out the most frequently added item. Stack supports 3 functions - push, pop,and top. Give complexity of each functions in your implementation.
I am having online test for Amazon SDE can anyone help ??
Given two Arrays {a1,a2,a3,.ai...aj...an} {b1,b2,b3,...bi...bj...bn). Note the size of both arrays are same.. We have to arrange the arrays in such a way such that aibi > ajbj. and ai > bi and aj > bj.
For.e.g.
A = {2, 3, 4, 5, 6, 7, 8, 9, 10, 11}
B = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1}
Order...
A = {1, 3, 5, 7, 9, 11, 13, 15, 17, 19}
B = {2, 4, 6, 8, 10, 12, 14, 16, 18, 20}
**Order**
A = 19,17,15,13,11,9,7,5,3,1
B = 18,16,14,12,10,8,6,4,2,20
**constraints**
There should be maximum no. of Ai's that should be greater than Bi's... Lemme know if you need more clarity on question?
Thanks.
How to prove the formula of binomial probability distribution ?
n
C (p^r)(1-p)^(n-r)
r
Generate n random numbers in the range 0...n-1 without repetition (using something like drand48 which returns a fraction in the range [0...1).
what is the difference between static inline and a extern inline function as well as inline function??
How compiler will treat it in each cases??
Why dont the network packets support padding? For example : if the maximum segment size is set 1024 bytes then for sending 1030 bytes will the network subsystem create 2 full length packets with second some padding and a flag?
why do we use circular link list in place of any balanced binary search tree in storage allocator? One draw back is that to free() a chunk of memory allocator has to search the link list and then if found that address then release , so why not tree to reduce this search and merge?
In 1st Phone screem:
int main(){
int *p=0;
printf("%d",++p);
}
whats the output ?
given a set of cubes with sides colored with random colors. Find if the cubes can be stacked one on top of other such that each of the four lateral sides has the same vertical color.
Tell me all the test cases to test amazon cloud player.
Write the code to test if a given binary tree is balanced or not? Write/give test cases for the same.
Read in a list of words.Create a 20x20 grid.Put the first word at 0,0 across Each of the following words in the list should be placed so that they intersect at as many letters as possible (the input words will always have at least one letter of overlap.)
If there is one more than one spot with the same number of intersected letters, place the word at all positions. (if some positions cause others to be invalid, choose the positions that allow the most words to be placed.)
Words can read across, backwards (right to left), down, and up.
A word is two or more characters in a row.
Positions are not valid if they cause non-words to appear in the grid.
If a word could fit in either direction (across/backwards) (up/down) choose across or down.
the question
example input:
alley
zebra
bole
bolero
wares
forgetmenot
carbonate
aardvarks
trombone
arts
example output:
alley c
r l s f aardvarks
b orelob r
elob r r b s
z r a g enobmort
seraw e t n r
l t a aardvarks
forgetmenot
b t e o e
a n b
n o r
enobmort aardvarks
b c
r
aardvarks
c
What are upper half and bottom half in device drivers.Why are they used?
What is the mechanism for open(),read(),write() system calls how does the kernel implements them and what happens when a user space program uses
open(file,r) like this with arguments,how does kernel implement it.
What is the difference between spin lock, mutex,semaphore.I was clear on this answer but then he asked for a real example of mutex.
I answered for busy waiting condition in spin lock,mutex there is no context switch.Then he said about pthread_mutex() call defined for using a mutex.Another program in which you do a fork and have a child process where are you going to use pthread_mutex in parent or in child.What is the difference between parent and child process?
Differenced between fork(),pthread() system calls.What is vfork().What is a file system how does kernel stores the data structure with respect to file system,he hinted to super blocks I was not much aware of super blocks etc in a file system,then I attempted for VFS kind of thing.
On some architecture stack grows upwards and on some architecture stack grows downwards.How will you find out whether the stack is growing upwards or downwards?
Given two linked lists, which are intersecting some where the shape can be L,Y or I, how will you find the intersection point?What will be time complexity.Assuming worst case how will you reduce the complexity.After having attempted this how will you convert above structure into X?
design a parking lot using OOAD. what would you think of?
write a c++ function to erase every other elements inside a map!
when i++ is better than ++i?
SubArray whoes sum is maximum
#include<stdio.h>
int maxSubArraySum(int a[], int size)
{
int max_so_far = 0, max_ending_here = 0;
int i;
for(i = 0; i < size; i++)
{
max_ending_here = max_ending_here + a[i];
if(max_ending_here < 0)
max_ending_here = 0;
if(max_so_far < max_ending_here)
max_so_far = max_ending_here;
}
return max_so_far;
}
/*Driver program to test maxSubArraySum*/
int main()
{
int a[] = {-2, -3, 4, -1, -2, 1, 5, -3};
int max_sum = maxSubArraySum(a, 8);
printf("Maximum contiguous sum is %d\n", max_sum);
getchar();
return 0;
}
Describe an algorithm to transfer Binary [Search] Tree exactly from one host to another over network. I assume question is about which traversal order should be used (inorder, postorder, preorder). Interviewer did no provide any feedback on this.
Given a very big file of words, a word in each line, sort the words
Given a Binary Search Tree, find the 2nd maximum element.
Given a binary tree where initially sibling pointers(left to right) are null for all nodes, connect all nodes at each level.
When I gave a solution with BFS, interview wanted a iterative solution as he feels BFS is easy solution.
Given a Roman number, convert it into the decimal number. Write the code considering the all cases including invalid strings.
list the file whose size greater than 1GB
list all zombie process
what is wrong here
void foo(int x=10,int y)
how compiler will treat it??
and what happen here
void foo(int x=10,int y=20)
How to build a heap from inoder traversal ?
{
int i=0;
++i;
i++;
int *p = &i;
++*p++;
++i++;
}
What happens in the last 2 statements and their respective outputs ?
Here ++*p++ does not throw an error, whereas ++i++ gives an error that lvalue required.
Can someone explain what happens and the reason for the error. Thank you
std::string bytesToHex(char * bytes, size_t size)
{
std::string result;
for (int i=0; i<size; i++) {
char hexByte[2];
sprintf(hexByte, "%02x", bytes[i]);
result.append(hexByte);
}
return result;
}what does this fn do?
Is there any problem with the code?
how do you fix it?
Which is better ++i or i++ and why ?
You are given a function that generates 0 and 1 with equal probability. Write a function that uses the above function to generate any n(1<=n<=1000) so that probability of producing any number between 1 to 1000 is equal and is 1/1000.
How do u test railway reservation system (like irctc) write the test cases
How to add a counter to www.google.com to track the billionth user.
You have a 64bit interger counter set to 0. How long it will take to overflow the counter given that you are incrementing it at 4Ghz speed
You have two classes list and array, how can you make sure that array class will compile before list class. Both the classes might be in differnet files.
How to get ISBN numbers from the billion of files that are downloaded and how to store them?I mean reading and storing of ISBN number.
Given an array of natural numbers (+ve, 0, -ve integers), find the maximum product of contiguous elements. Product value won't overflow 32 bits. Efficient solution ( O(nlogn) or better) is needed. Thanks.
Write a program that prints all the sub string that is palindrome within a input String. For e.g For input String "abbcacbca" output should be: [cac, bcacb, cbc, acbca, bb]
Write a C program for a input linkedList 1->2->3->4->5->6... o/p should be 2->1->4->3->6->5...
There is a river and there are n number of steps between two banks of the river to cross the river.
A frog wants to cross the river with the condition that he can jump max one step. Find the number of ways he can cross the river?
For e.g. if there are 3 steps in between, frog can go from paths: _123_, _2_, _13_ so there are 3 different ways frog can cross the river (in the example _ is two ends of the river)
you have to do the queue operation when you have a single stack..for example:-suppose there is a telephone bill populating in a stack now you have to process each request in a fifo manner.you can perform only push pop operation and allocating extra memory is not allowed.
Given a 4GB file of numbers. You are asked to find the product of K largest numbers. The size of the main memory is 1 GB. Give an efficient method to find.
do you know any scripting languages
How do you feel that this position does not require a lot of coding, you are mainly dealing with system administration.
-why do you want to work for autonomy zantac
-which job do you prefer a job with good work and life balance, or a job that is challenging but requires a lot of work
-how many houses are in pleaseanton
-why are man hole cover round
-three people, average salary without telling anybody your salary
-write atoi()
-print fibanncci number 0-1000
I was asked this question during one of my interviews. Can you do JOIN using UNION keyword? Can you do UNION using JOIN keyword?
Can you give me an example of how to do this if possible?
how to make all the elements of an integer array of size n 0 without using loop.(note: it is not about array initialization....but after the array already contains some non-zero elements..)
This is a question from TAOCP and I found it very interesting.
Given an array of integers, we can use stacks or deques (doubly ended queues) to output the numbers in certain permutations. For e.g. given an array {1, 2, 3, 4}, we can output it as {2, 3, 1, 4} by pushing down 1, pushing down 2, popping out 2, pushing down 3, popping out 3, popping out 1, pushing down 4 and then finally popping out 4. However, there are certain permutations that are not possible using a stack. For e.g., given an array {1, 2, 3, 4, 5, 6}, we can't create a permutation of {2, 1, 4, 6, 3, 5} using any sequence of push and pop operations on a stack. Using a deque however, it is possible. Write an algorithm to print out all the valid permutations that can be created using a stack and deque given an array of n integers.
I hope I am not misusing the forum by posting a question which I don't know if has been asked in an interview question. But the problem seems very interesting and could very well be an interview. problem.
how to create final class in c++
define class such that you can make object of this class on a heap but not on the stack.
An array with 'n' elements are passed to a function along with a number k. Function is expected to return 'number of pairs' which sum upto 'k'.
Ex: Say array contains {7,1,6,8,4,9} and k is 13, 7+6, 9+4 add upto 13. So, the return value should be 2.
Q1: What is the complexity if you find out the answer without modifying the array elements?
Q2: If you are allowed to odify the array elements, can the complexity be reduced? If yes, how?
Let's discuss on topic "solution to string problems using suffix tree & suffix array"
Write a function to check if an integer is square or not? Ex, 49 is square, 48 is not.
largest unique substring in string efficiently
how to allocate memory for string of unknown/arbitrary length during execution?
.
.
modify the following code & resultant code should allocate of any given input of arbitrary length
char* getstring(){
char* s;
gets(s);
return s;
}
given an UNSORTED real number array x1,x2,...,xn, how to find the max distance of two neighbouring numbers in the number axis. Is there any method with O(n) time complexity?
see an example
given x[]={2.0,1.0,9.0,-3.5}
then the answer is 7.0, because on the number axis, it is -3.5,1.0,2.0,9.0 from left to right.
distance between two neighbouring numbers are 1-(-3.5),2-1,9-2.
so the answer is 9-2=7
given a file of vast size that can not fit into the main memory, given a value 'k', find the k minimum values from the file.
find the maximum subtree in a given binary tree which is a binary search tree (face to face)
Given an N-Ary tree, WAP to find the minimum depth of the tree. (face to face round)
Given an infinite size array with only 0s and 1s and sorted. find the transition point where 0s end or 1s start (written test question. coding)
Given a binary tree, write a code that returns the difference between sum of nodes at even level and sum of nodes at odd level. Root is considered at level 0. (written test question. coding.)
RSA EMC security division interview.
Overall some people in this team seems are not smart enough to stay in this team since they are there since they don't have anywhere else to go. The company is pretty not flexible and not creative compared to other big IT companies such as Google or Amazon. To my surprise, there are quite many old people who unnecessarily paid a lot. If you're young and just graduated from school, I don't recommend this company.
45 Minute telephone interview:
Given a large list of 2D Points (x,y) find the k closest points to a target P(x,y).
- Implement the solution
- Explain the running time
- Explain how you can optimize your code
- Explain some decisions behind why you chose to write your code that way.
Is int i = 2 atomic?
You have to give the number times characters appear while scanning/traversing a long text.. like a book.
The interviewer indicated that it can be done using an array of 32(assume only lowercase alphabets) WITHOUT using the ascii values to increment the element in the array..
How is this possible without using ascii values of the characters?how would one differentiate among the characters then?
Any suggestions?
difference between smoketesting&sanitytesting with examples
explain about the functionnal testing with examples?
what is software testing with examples?
remove duplicates from a sorted linked list
Given an infinite sorted array containings only 0 and 1 . Find the point where 0 to 1 transition happening....
Given an integer n, write code to calculate n+1, without using +,-,++,--,*,/
Given 2 linked lists, merge them in-place, so that 1st element is from list1, 2nd from list2, 3rd from list1, 4th from list2, and so on..
Given n arrays, find n number such that sum of their differences is minimum. For e.g. if there are three arrays
A = {4, 10, 15, 20}
B = {1, 13, 29}
C = {5, 14, 28}
find three numbers a, b, c such that |a-b| + |b-c| + |c-a| is minimum. Here the answer is a = 15, b = 13, and c = 14
write a C program to create a bitmap of any size as determined by user. Say user says 64k bitmap, then create 64k long bitmap. Have set and unset methods.
Reorder 1st string based on 2nd string.
eg: (tractor,car)
output: carrtto or carrott or carrtot. The order of letters not in common doesn't matter.
Memory management in PHP
Pass by value and pass by reference in PHP
Find Sophie
After a long day of coding, you love to head home and relax with a loved one. Since that whole relationship thing hasn't been working out for you recently, that loved one will have to be your cat, Sophie. Unfortunately you find yourself spending considerable time after you arrive home just trying to find her. Being a perfectionist and unable to let anything suboptimal be a part of your daily life, you decide to devise the most efficient possible method for finding Sophie.
Luckily for you, Sophie is a creature of habit. You know where all of her hiding places are, as well as the probability of her hiding in each one. You also know how long it takes you to walk from hiding place to hiding place. Write a program to determine the minimum expected time it will take to find Sophie in your apartment. It is sufficient to simply visit a location to check if Sophie is hiding there; no time must be spent looking for her at a location. Sophie is hiding when you enter your apartment, and then will not leave that hiding place until you find her. Your program must take the name of an input file as an argument on the command line.
Input Specifications
The input file starts with a single number, m, followed by a newline. m is the number of locations available for Sophie to hide in your apartment. This line is followed by m lines, each containing information for a single location of the form (brackets for clarity):
<location name> <probability>probability is the probability that Sophie is hiding in the location indicated. The sum of all the probabilities is always 1. The contents of these lines are separated by whitespace. Names will only contain alphanumeric characters and underscores ('_'), and there will be no duplicate names. All input is guaranteed to be well-formed. Your starting point is the first location to be listed, and in effect it costs you no time to check if Sophie is there.
The file continues with a single number, c, followed by a newline. c is the number of connections that exist between the various locations. This line is followed by c lines, each of the form:
<location name> <location name> <seconds> The first two entries are the names of locations and seconds is the number of seconds it takes you to walk between the them. Again these lines are whitespace-delimited. Note that the locations are unordered; you can walk between them in either direction and it will take the same amount of time. No duplicate pairs will be included in the input file, and all location names will match one described earlier in the file.
Example input file:
4
front_door .2
in_cabinet .3
under_bed .4
behind_blinds .1
5
front_door under_bed 5
under_bed behind_blinds 9
front_door behind_blinds 5
front_door in_cabinet 2
in_cabinet behind_blinds 6
Output Specifications
Your output must consist of a single number followed by a newline, printed to standard out. The number is the minimum expected time in seconds it takes to find Sophie, rounded to the nearest hundredth. Make sure that the number printed has exactly two digits after the decimal point (even if they are zeroes). If it is impossible to guarantee that you will find Sophie, print "-1.00" followed by a newline instead.
Example output:
6.00
Gattaca
You have a DNA string that you wish to analyze. Of particular interest is which intervals of the string represent individual genes. You have a number of "gene predictions", each of which assigns a score to an interval within the DNA string, and you want to find the subset of predictions such that the total score is maximized while avoiding overlaps. A gene prediction is a triple of the form (start, stop, score). start is the zero-based index of the first character in the DNA string contained in the gene. stop is the index of the last character contained in the gene. score is the score for the gene.
Input Specification
Your program will be passed the name of an input file on the command line. The contents of that file are as follows.
The first line of the input contains only n, the length of the DNA string you will be given.
The next ceiling(n / 80) lines each contain string of length 80 (or n % 80 for the last line) containing only the characters 'A', 'C', 'G', and 'T'. Concatenate these lines to get the entire DNA strand.
The next line contains only g, the number of gene predictions you will be given.
The next g lines each contain a whitespace-delimited triple of integers of the form
<start> <stop> <score> representing a single gene prediction. No gene predictions will exceed the bounds of the DNA string or be malformed (start is non-negative and no more than stop, stop never exceeds n - 1).
Example Input:
100
GAACTATCGCCCGTGCGCATCGCCCGTCCGACCGGCCGTAAGTCTATCTCCCGAGCGGGCGCCCGATCTCAAGTGCACCT
CACGGCCTCACGACCGTGAG
8
43 70 27
3 18 24
65 99 45
20 39 26
45 74 26
10 28 20
78 97 23
0 9 22
Output Specification
Print to standard out the score of the best possible subset of the gene predictions you are given such that no single index in the DNA string is contained in more than one gene prediction, followed by a newline. The total score is simply the sum of the scores of the gene predictions included in your final result.
When constructing your output, you may only consider genes exactly as they are described in the input. If you find the contents of a gene replicated elsewhere in the DNA string, you are not allowed to treat the second copy as a viable gene. Your solution must be fast and efficient to be considered correct by the robot.
Example Output:
100
It's A Small World
As a popular engineer, you know many people in your home city. While traveling around town, visiting your friends, you realize it would be really handy to have a program that tells you which of your friends are closest based upon which friend you are currently visiting.
Being an engineer who is interested in writing software that is useful to everyone, you decide to write a general solution to your quandary. Each of your friends lives at a unique latitude and longitude. For the purposes of this program, the world is flat, and the latitude and longitude are for all intents and purposes Cartesian coordinates on a flat plane. For example, in our flat world, lat 45, long -179 is not as close to lat 45, long 179 when compared to lat 45, long 170.
Write a program that takes a single argument on the command line. This argument must be a file name which contains the input data. Your program should output the nearest three other friends for each friend in the list. You are virtually a celebrity and your friend list can be astoundingly huge. Your program must exhibit better than quadratic asymptotic growth in runtime as a function of the size of your friend list, and be robust and resource efficient.
Input specifications
The input file consists of multiple lines, all of which follow the same format. Each line has three values separated by an amount of white space. The first value is the unique id number of that friend, expressed as an integer. The second value is the latitude of that friend, expressed as a rational number. The third and last value is the longitude of that friend, expressed as a rational number. Every friend lives at a unique combination of latitude and longitude (e.g. no two friends will ever share the exact same values). Each line ends with a single new line, except for the last line of the file, which may or may not have a terminating new line.
Example input file:
1 0.0 0.0
2 10.1 -10.1
3 -12.2 12.2
4 38.3 38.3
5 79.99 179.99 You are guaranteed that your program will run against an input file that is well formed, and has at least four lines. You are also guaranteed that your list of friends have unique distances between one another; no two distinct pairs of friends will have the same distance between them.
Output specifications
In the order presented in the input file, output the nearest three friends for each friend. Each line of output should start with the integer id of the friend followed by a single space character, and then the list of three nearest other friend ids followed by a single new line. Even the last line of the output should terminate in a new line. This list should be comma-delimited, with no spaces. The list must be in order of proximity, with the closest of the three being first, and the farthest of the three being last.
Example output:
1 2,3,4
2 1,3,4
3 1,2,4
4 1,2,3
5 4,3,1
find missing numbersin given billion number.( numbers lie between 1-k)
Sort 10 GB file using 2 GB memory. and complexity
print a tree layer by layer
given a series of stock prices in an array. Pick when to buy and when to sell to gain max profit.
(This a the worst experience for me ever! It is just a simple max sum problem. The interviewer came in with his computer and kept smiling at it while his phone rings all the time. I couldn't even think. This guy totally screwed my interview.)
expression tree design.
given two sorted arrays. A and B. there are empty spaces in A which is same size of B. Merge them.
Write code.
1. Write a function to print a multiplication table.
Ex.
1 2 3
1 1 2 3
2 2 4 6
3 3 6 9
you should maintain the alignment for any larger value
Liar, Liar
As a newbie on a particular internet discussion board, you notice a distinct trend among its veteran members; everyone seems to be either unfailingly honest or compulsively deceptive. You decide to try to identify the members of the two groups, starting with the assumption that every senior member either never lies or never tells the truth. You compile as much data as possible, asking each person for a list of which people are liars. Since the people you are asking have been around on the board for a long time, you may assume that they have perfect knowledge of who is trustworthy and who is not. Each person will respond with a list of people that they accuse of being liars. Everyone on the board can see that you are a tremendous n00b, so they will grudgingly give you only partial lists of who the liars are. Of course these lists are not to be taken at face value because of all the lying going on.
You must write a program to determine, given all the information you've collected from the discussion board members, which members have the same attitude toward telling the truth. It's a pretty popular discussion board, so your program will need to be able to process a large amount of data quickly and efficiently.
Input Specifications
Your program must take a single command line argument; the name of a file. It must then open the file and read out the input data. The data begins with the number of veteran members n followed by a newline. It continues with n chunks of information, each defining the accusations made by a single member. Each chunk is formatted as follows:
<accuser name> <m>
followed by m lines each containing the name of one member that the accuser says is a liar. accuser name and m are separated by some number of tabs and spaces. m will always be in [0, n]. All member names contain only alphabetic characters and are unique and case-sensitive.
Example input file:
5
Stephen 1
Tommaso
Tommaso 1
Galileo
Isaac 1
Tommaso
Galileo 1
Tommaso
George 2
Isaac
Stephen
Output Specifications
Your output must consist of two numbers separated by a single space and followed by a newline, printed to standard out. The first number is the size of the larger group between the liars and the non-liars. The second number is the size of the smaller group. You are guaranteed that exactly one correct solution exists for all test data.
Example output:
3 2
To safeguard against the dreaded phenomenon of wall posting while drunk, flipkart is implementing a feature that detects when post content is too garbled to have been done while sober and informs the user that they need to take an online breathalyzer test before being allowed to post.
Unfortunately, there is far too much content for a given set of persons to evaluate by hand. Fortunately, you are a programmer of some repute and can write a program that processes and evaluates wall posts. You realize that such a program would be of great use to society and intend to resolve the problem once and for all. The program you write must compute a score for a body of text, returning this score upon completion.
Your program will be given a list of accepted words and run on one wall post at a time. For each word W in the post, you must find word W' from the list of accepted words such that the number of changes from W to W' is minimized. It is possible that W is already W' and thus the number of changes necessary is zero. A change is defined as replacing a single letter with another letter, adding a letter in any position, or removing a letter from any position. The total score for the wall post is the minimum number of changes necessary to make all words in the post acceptable.
Input Specification
Your program must take a single string argument, representing the file name containing the wall post to analyze. In addition, your program must open up and read the accepted word list from the following static path location:
/var/tmp/twl06.txt
For testing purposes, you may download and examine the accepted word list here. When submitting your code, you do not need to include this file, as it is already present on the machine.
The input file consists entirely of lower case letters and space characters. You are guaranteed that the input file will start with a lower case letter, and that all words are separated by at least one space character. The file may or may not end with a new line character.
Example input file:
tihs sententcnes iss nout varrry goud
You are guaranteed that your program will run against well formed input files and that the accepted word list is identical to the one provided for testing.
Output Specification
Your program must print out the minimum number of changes necessary to turn all words in the input wall post into accepted words as defined by the word list file. Words may not be joined together, or separated into multiple words. A change in a word is defined as one of the following:
1. Replacing any single letter with another letter.
2. Adding a single letter in any position.
3. Removing any single letter.
This score must be printed out as an integer and followed by a single new line.
Example Output (newline after number):
The secretary problem is an optimal stopping problem that has been studied extensively in the fields of applied probability, statistics, and decision theory. It is also known as the marriage problem, the sultan's dowry problem, the fussy suitor problem, the googol game, and the best choice problem. The solution is sometimes called the 37% rule. The problem can be stated as follows:
1. There is a single secretarial position to fill.
2. There are n applicants for the position, and the value of n is known.
3. The applicants can be ranked from best to worst with no ties.
4. The applicants are interviewed sequentially in a random order, with each order being equally likely.
5. After each interview, the applicant is accepted or rejected.
6. The decision to accept or reject an applicant can be based only on the relative ranks of the applicants interviewed so far.
7. Rejected applicants cannot be recalled.
8. The objective is to select the best applicant. The payoff is 1 for the best applicant and zero otherwise.
Terminology: A candidate is an applicant who, when interviewed, is better than all the applicants interviewed previously. Skip is used to mean "interview and reject".
Clearly, since the objective in the problem is to select the single best applicant, only candidates will be considered for acceptance. One reason why the secretary problem has received so much attention is that the optimal policy for the problem (the stopping rule) has a surprising feature. Specifically, for large n the optimal policy is to interview and reject the first n/e applicants (where e is the base of the natural logarithm) and then to accept the next who is better than these interviewed candidates. As n gets larger, the probability of selecting the best applicant from the pool goes to 1/e, which is around 37%. Whether one is searching through 100 or 100,000,000 applicants, the optimal policy will select the single best one about 37% of the time.
Insert a node into a circular linked list.
This CLL is sorted. So, if the CLL is like 1->2->4->6->1
you will be asked to input a node 3 and it must come between 2 and 4.
Write a program for this in C++ or JAVA
An application uses its own server and some external third party server. Suppose if external or third party server is unavailable, how will you test application?
How to know the stack size in C?? I am using Windows 32 bit and VC++ compiler...
how do you test the numbers present in a linked list is palindrome or not ? (list is a singly linked list)
how do you test given BST is a valid BST?
given a bst and a value x.find pair of nodes in the tree that sum upto x
Given 3 arrays A,B,C find three indices i,j,k such that the value of I = max((a-b),(b-c),(c-a)) is minimized
Sorted Array Merge Problem: Design an algorithm to merge two sorted positive integer arrays A and B. Size of array A is n and size of array B is m. Array A has m empty blocks(-1) at random places. Merge array B into A such that array A is sorted and does not have empty blocks.
3)Given a file contiaining number of words , with one word per line .Print a string together that are anagrams
1)Given a large file containing 10 bit integers,and a limited memory , sort the entire file and store back
to file.
Constraints : You cannot read entire file in main memory at a time as meory is limited (small)
Follow up questions: Quick sort working,complexity best,avg,worst
Hint :Use property of 10 bit integer
You have a 1000 story building and three eggs. These are especially strong eggs. There is some floor below which the egg will not break if dropped. What is the worst case
upper bound on the number of drops you must make to determine this floor?
There is a straight roads with 'n' number of milestones. You are given an array with the distance between all the pairs of milestones in some random order. Find the position of milestones.
Example:
Consider a road with 4 milestones(a,b,c,d) :
a <--- 3Km --->b<--- 5Km --->c<--- 2Km --->d
Distance between a and b = 3
Distance between a and c = 8
Distance between a and d = 10
Distance between b and c = 5
Distance between b and d = 7
Distance between c and d = 2
All the above values are given in a random order say 7, 10, 5, 2, 8, 3.
The output must be 3,5,2 or 2,5,3
What is the most efficient way, memory-wise, to store 1 million phone numbers? Apparently this is an interview question at Google, although this seems like its a bit too easy.
Given k sorted streams where each stream could possibly be infinite in length, describe an efficient algorithm to merge the k streams into a new stream (also in sorted order).
Question #2) Given a set of KEY->VALUE pairs such that each KEY is unique, describe a method of storing these pairs on disk, and a method for accessing the corresponding VALUE given a KEY. Assume that RAM is fixed at 1gb and the set of pairs requires 40gb.
Write a C++ program that would find and print the first longest ascending or descending contiguous subsequence for a vector of integers. For example, given a vector with
4, 2, 1, 2, 3, 4, 3, 5, 1, 2, 4, 6, 5
the program would find the underlined subsequence and print it.
how to generate permutation of a string with duplicate characters without caching previous generated string in memory.
eg.
abc -> {abc, acb, bac, bca, cab, cba}
all -> {all, lal, lla}
Q1. I have four operations
Set(i) sets the ith bit
Unset(j) unsets the jth bit
Set(i,j) sets the bits b/w i and j
Unset(i,j) unsets the bits b/w i and j
Design a data structure for this problem with minimum time and space complexity.
Given an integer array.
e.g. 1,2,3,4,5
Compute array containing elements
120,60,40,30,24 (2*3*4*5,1*3*4*5, 1*2*4*5, 1*2*3*5, 1*2*3*4)
So I gave simple solution using division operator. He said that what if there is a 0 as an element and
what if there are two zeroes.
Then he asked me to do it without using division operator. So after little fumbling I did it in O(n)
extra space and O(n) time.
Then he asked me to do it in O(1) space and O(n) time.
write a function that takes two numbers a and b and returns a.b eg: a=10 and b=12 output will be 10.12
To safeguard against the dreaded phenomenon of wall posting while drunk, flipkart is implementing a feature that detects when post content is too garbled to have been done while sober and informs the user that they need to take an online breathalyzer test before being allowed to post.
Unfortunately, there is far too much content for a given set of persons to evaluate by hand. Fortunately, you are a programmer of some repute and can write a program that processes and evaluates wall posts. You realize that such a program would be of great use to society and intend to resolve the problem once and for all. The program you write must compute a score for a body of text, returning this score upon completion.
Your program will be given a list of accepted words and run on one wall post at a time. For each word W in the post, you must find word W' from the list of accepted words such that the number of changes from W to W' is minimized. It is possible that W is already W' and thus the number of changes necessary is zero. A change is defined as replacing a single letter with another letter, adding a letter in any position, or removing a letter from any position. The total score for the wall post is the minimum number of changes necessary to make all words in the post acceptable.
Input Specification
Your program must take a single string argument, representing the file name containing the wall post to analyze. In addition, your program must open up and read the accepted word list from the following static path location:
/var/tmp/twl06.txt
For testing purposes, you may download and examine the accepted word list here. When submitting your code, you do not need to include this file, as it is already present on the machine.
The input file consists entirely of lower case letters and space characters. You are guaranteed that the input file will start with a lower case letter, and that all words are separated by at least one space character. The file may or may not end with a new line character.
Example input file:
tihs sententcnes iss nout varrry goud
You are guaranteed that your program will run against well formed input files and that the accepted word list is identical to the one provided for testing.
Output Specification
Your program must print out the minimum number of changes necessary to turn all words in the input wall post into accepted words as defined by the word list file. Words may not be joined together, or separated into multiple words. A change in a word is defined as one of the following:
1. Replacing any single letter with another letter.
2. Adding a single letter in any position.
3. Removing any single letter.
This score must be printed out as an integer and followed by a single new line.
Example Output (newline after number):
8
given number 1,2,3,4,5,6,7,8,9 find all sets that sums up to 10
eg. [1,9] [1,2,7],[1,2,3,4] find all possible set can be made.
Check whether point lies inside polygon
You are given a convex polygon and an additional point. You know the x and y co-ordinates of all vertices of the polygon and the point. Find if the point is one of the vertices of the polygon in O(log N) time..
Given a rectangle with known width and height, design an algorithms to fill the rectangle using n squares(n is integer, also given) and make sure in the result the wasting area is minimized. Length of square doesn't have to be integer.
I.e, given width=3,height=2,n=5, one solution is that rectangle can be filled with five 1x1 squares and the wasting area is 1. Another solution could be filled with five 0.9x0.9 squares, but the wasting area is more than first solution.
Find a point in an array where sum of left side array members(wrt to that point) and right side(wrt to that point) are equal..in other words equilibrium point.
Design a file system
Consider there is an array with duplicates and u r given two numbers as input and u have to return the minimum distance between the two in the array with minimum complexity.
There is a document and some key words are given. Find the minimum length of substring in the
document which contains all the keywords. The substring can contain key word in any order.
How do you implement the dynamic memory allocation using heap
two BST were given and find the largest common bst that exists between these two
glitch is a walking robort moves in a peculiar problem: it takes x steps forward , then x+1 steps backward, then 2x steps forward, x+2 steps backward,3x steps forward x+3 steps backward , and so on... until it has taken y steps,glitch turns 180 degrees before continuning with its pattern . write a program that prompts x and y and total number of steps taken and outputs how many steps away from its starting point
replace a,e,i,o,u with A,E,I,O,U
at most four eligible letters from the rear of the string are replaced
the first three eligible letters in the string are always exempted from replacement
Given a node in a graph that is reachable, how do you find all the nodes that are reachable ? How would you enable parallel computation of this information ? Given a number of cores, how many threads would you choose ?
You are given an array of integers, say array1 of size n. You have to create another array (say array2) and fill its contents by following this rule: array2[i] will hold the value of the left-most integer from the range array1[i+1] to array1[n-1] such that it is greater than array1[i]. If no such element exists, assign -1.
You are given a 1D array of integers, such as:
int[] array = [3,4,7,2,2,6,0,9];
Suppose you need to treat this array as a 2D table with a given number of rows.
You want to sum the columns of the table.
One value of numRows is 4..in that case the resultant array would look like
what if numRows==4?
3 4
7 2
2 6
0 9
—-
12 21
We have a text file with 13 Million entries, all numbers in the range from 1.000.000 to 100.000.000. Each line has only one number. The file is unordered and we have about 1% duplicate entries. Remove the duplicates.
Given an array A of N integers we draw N discs in a 2D plane, such that i-th disc has center in (0,i) and a radius A[i]. We say that k-th disc and j-th disc intersect, if $k\not =j$ and k-th and j-th discs have at least one common point.
Write a function
class Solution { public int number_of_disc_intersections(int[] A); }
which given an array A describing N discs as explained above, returns the number of pairs of intersecting discs. For example, given N=6 and
\begin{displaymath}A[0]=1 A[1]=5 A[2]=2 A[3]=1 A[4]=4 A[5]=0\end{displaymath}
there are 11 pairs of intersecting discs:
0th and 1st
0th and 2nd
0th and 4th
1st and 2nd
1st and 3rd
1st and 4th
1st and 5th
2nd and 3rd
2nd and 4th
3rd and 4th
4th and 5th
so the function should return 11.
The function should return -1 if the number of intersecting pairs exceeds 10,000,000. The function may assume that N does not exceed 10,000,000.
Given a binary tree, print each level on a single line.
c++#include <stdio.h>
#include <unistd.h>
int main()
{
while(1)
{
fprintf(stdout,"hello-out");
fprintf(stderr,"hello-err");
sleep(1);
}
return 0;
}
Swap alternate nodes in a Singly linked List
Given 2 Tree, find out if they r exactly same or not
Given a Tree (not binary Tree), print only leaf nodes with it's path from Root
Given a graph of price variation of a stock over a period of 12 months, return the ideal time to buy and sell, for maximization of profit. Time duration is not constraint. Time duration needn't be minimum it can even be maximum 12 motnhs
Given a sequence of charecters , print consequtive sequence of charecters alone in a line, other wise print it in a new line.
eg: ABCXYZACCD
o/p :
ABC
XYZ
A
C
CD
How to find the depth of a tree.
Time and Memory optimization is emphasized
Find if a singly linked List has loop or not.
How to find out middle element from a looped single linked list
Find the middle element in a singlely linked list and code it,
What are the various ways to swap 2 variables
Answer :
a) Using temporary Variable
b) Usnig some Arithmentic operation
c) Using bitwise XOR operation
Which operation is better and Why ?
Given a file, return the Top 5 frequently occuring list of words
Design a Chess Game
Design Snake and Ladder Game
you are given following:
1. An empty tank
2. Unlimited source of water.
3. Some container of certain measurments and a container of 1 litre is always given.
Your job is to fill the tank from source of water using the containers in minimum number of steps.
You cant fill the container with a small amount of water than its size (filling partially is not allowed).
Find the number of steps and print the solution.
e.g.
Tank Size: 80 litre
Containers: 1,3,5,6,25 litre
Solution:
4
5,25,25,25
Tank Size: 71 litre
Containers: 1,3,5,6,25 litre
Solution:
6
3,6,6,6,25,25
Write a function that, given a string, returns number of characters, words and lines in that string.
Given a KxK array, rotate the array 90 degrees counter-clockwise in place.
add 2 link lists widout recursion in O(n) n constant space
print the nodes of binary tree in on sorted oder
reversing of double linked list
Given n elements & their is dependency between them it can linear or circular or any other dependency you can think of , you to explain the algorithm that tell the write order of execution of all program , he discussed about the data structure , time complexity & algorithm & its really gud question, also if it is circular then deadlock condition occur so no process execute .
3)given a linkedLists with next and arbit pointers, duplicate it.
Write neat code for all algorithms.
2)given two numbers represented as linkedLists, like 135 is written as 1->3->5, find the sum of the two numbers.
I reversed and added. Said don' reverse and do it now(Use recusrion!)
f2f round 4
1)given an array with positive and negative numbers find the first continuous subarray that sums to 0!
3) construct double linklist out of a BST
f2f round 2
2) Given a no. find all pairs of elements in a balanced bst, which sum to this number. Make sure you don; return same pair again.
f2f round 2
1)diameter of a tree, write good code for getting height
define class such that you can make object of this class on a heap but not on the stack.
define a class such that you can make object of this class but you can not inherit this class.
How will u find cube root of a number in efficient way?
The function signature looks like this:
boolean isPalindrome(int x)
It should return true if the the bit pattern of x is the same as when you reverse it.
What happens when two balls interact on the screen (not the obvious answer of their physical interaction, I don't know the goal of the question).
Given two squares on a screen, how do you know if they intersect (the answer is not the obvious one, comparing the x and y values of the sides, I really don't know the goal of the question).
Read a file of this format:
japan
usa
japan
russia
usa
japan
japan
australiaPrint the output in the following format:
<country> : <count>
So for above file output would be:
japan : 4
usa : 2
australia : 1
russia : 1Note that since australia and russia both have count as 1, the name are sorted, 'a' before 'r'. Do it in the most efficient way.
what happens when ls is invoked from shell, when ls|wc is invoked? Discussed in detail about fork and exec.
f2f round 1
Given 3 arrays, pick 3 nos, one from each array, say a,b,c such that |a-b|+|b-c|+|c-a| is minimum
I have attended SONY interview recently. One of the RTOS question was what is priority inversion?? I answered but he asked why a high priority task is waiting for the low priority task to complete its job instead of preempting it?? I answered in order to avoid starvation..but he told that is not the correct answer...If somebody knows plz help..
What the advantage of reference over the pointer?? In what cases I should use reference??
Why should I call the derived class function through the base class pointer which brings the virtual function concept?? Instead I can call the derived class function through the derived class pointer. Plz help someone on this!!!
What is virtual memory?
Gave a program which was capitalizing all vowels in a string. There were lot of bugs which he asked me to correct. Then asked to write test cases
Gave a program which was capitalizing all vowels in a string. There were lot of bugs which he asked me to correct. Then asked to write test cases
Given a BST and integer value K.
Find two nodes x and y such that x->data + y->data = K
Time O(n), space O(1)
Difference between Interrupt,Trap,Signals & System call.Relation between them such as "what is generated after what"?
1. What do you mean by maskable and NMI's, give examples?
2. what is the relation between interrupts and Signals?When you pres Ctrl-d or Ctrl-z what happens?Are Signals eg SIGINT,SIGFPE maskable?
3.What are Software Interrupts and TRAP? give examples.
4.IDT ans ISR's
The questions were asked as per my responses and I think I messed it up,plz clear my concepts and help for future job interviews.
3. Given a set of N lines of English language, each comprises only of a-z and A-Z. For each line, find the alphabets which have highest frequency of occurance and print them (with capital letters first then small letters in increasing order in their type and then frequency).
example:
Hello How are u
eeeefff
ZefZe
then output is:
Helo 2
e 4
Ze 2
2. Leaves are represented with L and non-leaf with N in a tree. Each node has either 0 or 2 children. so if given preorder traversal of this tree, construct the tree.
1. WAP to check if given linked list is palindrome
Given a binary tree, find 2 leaf nodes say X and Y such that F(X,Y) is maximum where F(X,Y) = sum of nodes in the path from root to X + sum of nodes in the path from root to Y - sum of nodes in the common path from root to first common ancestor of the Nodes X and Y
You have given 2 array. You need to find whether they will create the same BST or not.
For example:
Array1:10 5 20 15 30
Array2:10 20 15 30 5
Result: True
Array1:10 5 20 15 30
Array2:10 15 20 30 5
Result: False
write a program for consumer and producer threads accessing shared queue, given primitives( written test)
CreateEvent
EnterCriticalSection/ EndCriticalSection
Sleep
Wait
SetEvent etc
write a function which allocates two dimensional array dynamically
int ** allocate(int row, int col)
1) write declaration of sprintf
2) difference between typedef and #define
3)how free remembers how many bytes to delete
4)write a macro for swapping two values of same data type
given power(x,y)implementation, find number of multiplications in power(5,12)( written test)
int pow(int x, int n)
{
if(n==0)return(1);
else if(n%2==0)
{
return(pow(x,n/2)*pow(x,(n/2)));
}
else
{
return(x*pow(x,n/2)*pow(x,(n/2)));
}
}
suggest a data structure for storing polynomial.Now write a program to add two polynomials.( written test)
ax+ bx^2 + cx^3+...
print all paths from root to leaves( written test)
write a program to find height of a bst.( written test)
Multiple Choice,Amazon online test:
1)Given two sorted arrays of size m and n each, what is the minimum time taken to find the kth smallest element in the combined array
2)what is Minimum number of edges in a connected graph N nodes
3)What is the minimum number of using the next pointer required to find median of a sorted singly linked list of size n
4)
write a program to find if a password entered is a valid password( meet the given criteria like should have characters, special characters etc): Online written test
create a bst from preorder and inorder
input is given a comma separated strings
1,2,3,4,5 ( inorder)Online written test
find the minimum sum sub array (online written test)
find if two strings are anagram of each other in o(n) time( online written test)
WHAT AMOUNT TAKEN IF COMPANEY GET A ASSET FREE?
Macro for min of 2 nos,deletion of node,reverse string....OS questions-protected memory-preemptive-special requirements of embedded systems, osi layer
How to sort a 1gb of 10 files(totoal 10gb) but ram size is 2gb only. Which algorithm or data structure we need to use to sort these files?
Is there any algorithm to find distance between each pair of point among n points whose time complexity is better than O(n^2) i.e. C(n,2).
You are given a binary tree in which each node contains a value Design an algorithm
to print all paths which sum up to that value Note that it can be any path in the tree
- it does not have to start at the root
How do you determine if every digit in the binary representation of a number is a one?
I'll post the answer in a bit, think about it first!
4. In the language of your choice write me a function that does the following: “Walk a linked list (passed in as a parameter) and return a min, max, and average of the values at the end.” How would you then test this function?
You are provided with the preorder traversal of a min-heap in an array. Your function should return the actual min-heap?
Write a code for this problem.
You have a digital clock having 24 hr format of HH:MM:SS. You have to find following probabilities:
1- Occurence of a particular value(let say 05) in SS
2- As 1st point we have to find probabilities for particular value in hour and minute fields.
3- probalities for other combinations(particular HH:SS or MM:SS values)
You have to answer the probability in terms of digits occurence...for example in the second's field.. at unit place 10 digits(0-9) are possible, and in the tens place 6 digits are possible (0-5)
It is not a very straight forward problem. Many different scenarios are possible(value in the seconds field will change in every 1 min, on the other hand, the value in the hour field will remain same till 60 min)
Please don't answer ur probabilty in terms of time(as 1/60, 1/24*60) rather in terms of digits only as described above.
Give an efficient algorithm to check whether two strings are rotationally equivalent or not i.e. one string can be obtained by rotating the other string by any number of characters or not.
For example, the strings "abcd" and "dabc" are rotationally equivalent but the strings "abcd" and "acbd" are not.
write a program to merge two sorted arays ?
This is for the written test
code to reverse a Linked List
This is for the written test
A string is well formed if for every "(" left parenthesis you have matching right one ")".In the same way every ")" should have a preceding "(".write a program finds if a string is wellformed .
This is for the written test
And finally my experience (if you are interested)..
Given a character array with a set of characters, there might be repetitions as well, given two characters, you should give the minimum distance between these two characters in the whole array. O(n^2) and O(n) solutions are possible.
Print an mxn matrix spirally. Write code for the same.
Given a continuous stream of 1's and 0's how do you determine whether the number so far is divisible by 3? At any point of time, you will have previous sequence in hand and a 1 or a 0 appears, without looking at the entire sequence we should be able to tell whether the sequence formed by adding the new number will is divisible by 3 or not?
Given an array of positive and negative numbers (not sorted), find the continuous sub-array or sub-sequence that gives largest possible sum in the whole array.
Given a string eg "aaabbccaaadd" replace the same string as "3a2b2c2a2d". Will you logic work given the compressed string and back to the original string?
Given a sorted array, find a pair of elements that sum upto a given value.
There are 99 no's. All the no's 1-99 are integers. There is an array of 100 slots. When the array is filled up with all the no's, there is one empty slot as there are only 99 no's and 100 slots. Now this empty slot is filled up with one of those 99 no's. Find this duplicate no. in O(n) time. You don't need to give the position of the element in the array.
Write a program to find out the sum of nodes which does not have siblings in a binary tree
I have written following logic and he was impressed with the logic, I think I did well but could not able write the logic for the traversing as I was not prepared but he said explain what is want to do and I explained, hoping for good results.
public int returnNodeValue(Node t)
{
BOOL thereIsNoLeft = false;
BOOL thereIsNoRight = false;
int returnValue = 0;
if(t.left != null)
{
thereIsNoLeft = true;
returnValue = t.left.value;
}
if(t.right != null)
{
thereisNoRight = true;
returnValue = r.right.value;
}
if(!(thereIsNoLeft && thereisRight))
{
return returnValue;
}
return 0;
}Which data structure is fast when you want to sort or search Linked List or Array?
What is Hashtable, using which data structure hash table is implemented
Describe Fly-Weight pattern
When do you use Abstract and when do u use Interface
Types of exceptions in JAVA
Given a binary matrix of N X N of integers , you need to return only unique rows of binary arrays
eg:
0 1 0 0 1
1 0 1 1 0
0 1 0 0 1
1 1 1 0 0
ans:
0 1 0 0 1
1 0 1 1 0
1 1 1 0 0
Check Whether Point Lie Inside, on or outside the triangle efficiently what will be time complexity & which data structure algorithm
as you can see google asked they wants quality code & efficient algorithm
An easier way than what Richie mentioned is to the following:
if a point P is inside triangle ABC, then
Area PAB+Area PBC +Area PAC=Area ABC
notice that if P is on the edge of AB, BC, or CA, the above hold. But effectively, one of the area PAB, PBC, PAC is 0 (so just make sure you check that).
if P is outside, the above equality does NOT hold..
But how you will approach for if point lie outside the triangle
A rooted binary tree with keys in its nodes has the binary search tree
property (BST property) if, for every node, the keys in its left
subtree are smaller than its own key, and the keys in its right
subtree are larger than its own key. It has the heap property if, for
every node, the keys of its children are all smaller than its own key.
You are given a set of n binary tree nodes that each contain an
integer i and an integer j. No two i values are equal and no two j
values are equal. We must assemble the nodes into a single binary tree
where the i values obey the BST property and the j values obey the
heap property. If you pay attention only to the second key in each
node, the tree looks like a heap, and if you pay attention only to the
first key in each node, it looks like a binary search tree.Describe a
recursive algorithm for assembling such a tree
given a binary tree, find a path which sum to a given target. the path can start from node, go to the left subtree and also to the right subtree...
for example if the given BT is
5
/ \
3 2
/
7and if the target is 10, then the path is ---- root(5) + left node(3) + right node (2).
Difference between Dictionary and a Hashtable ?
Whats a Linked List ? Given Two linked list forming a Y shaped linked list . Find the intersecting node...where one list has more nodes than the other ? Runtime analysis etc etc .
Spiral Matrix psuedo code(& logic) :|
Suggest a DS for web server to store history of visited pages. The server must maintain data for last n days. It must show the most visited pages of the current day first and then the most visited pages of next day and so on.
Write a function which takes as parameters one regular expression(only ? and * are the special characters) and a string and returns whether the string matched the regular expression.
You have to find the direction of rotating magnetic plate by using minimum sensors on plate, each sensor return a timestamp whenever the Head of the plate passes through it,
You have multiple mail servers in different places around the world, servers have public and private datastores, resources in public datastore are shared obviously and can be read,modified by any user, how will you test the servers?
Static Vs Singleton Pattern
OOD (classes,functions, type of class etc) for a Burger Shop such as Mcdonalds etc?
Find the distance of a node from the root in a binary tree.Print error message if node doesn't exist.
Extend the problem to distance of any node to any other node that is below it.
Given an integer 'k' and an sorted array A (can consist of both +ve/-ve nos), output 2 integers from A such that a-b=k.
PS:
nlogn solution would be to check for the occurence of k-a[i] (using binary search) when you encounter a[i]. methods like hash consume space.
Is an O(n) solution with O(1) extraspace possible?
find all the subset of an array having integers from 1 to 9 such that sum of each subset is 10.
To write a function which given two dates, checks whether the dates are exactly 1 month apart(e.g June 06 2011 & July 06 2011, Dec 15 2010 & Jan 15 2011 ), less than 1 month apart(e.g Mar 01 2011 & Mar 25 2011, Jun 20 2011 & July 10 2011) or greater than 1 month apart(e.g May 16 2011 & July 16 2011 etc...)
How to implement search suggestions. ie. when a prefix of a word is typed matching words from the dictionary should be displayed.
Interviewer was interested in usage of appropriate data structure
Implementing a LRU cache ( it is a key,value pair cache).
what are the advantages/disadvantages of using template and virtual functions(dynamic binding) in compile time and run time?
What is Stack ?
How would you test a Stack?
The size of stack is not provided. Can you define stack size at run time?
Maximum Sum path in a binary tree where the each node has a integer value associated to it.We have to print the ROOT TO LEAF path with maximum sum.
is STL map thread-safe? why?
implement a reference count shared pointer
Given a 2D array write a tight code to traverse it in zigzag manner.
Given a linked list of characters check whether it is a palindromic one.
Given two arrays of length m & n Find the median without merging these two arrays.
5- Fibonacci function implement it .
then I did Iterative way to get better performance , then he asked about Fibonacci recursive and what is the complexity of it ? it is O(n2) because of the tree calls and repeated calls.
4-given an array of int and given a number , find the 2 elements in array that add up to the given number.
3- Different ways to communicate between Processes in OS.
2- Virtual function table in C++ , and how they work and how the compiler generate them and how the object know it is overridden and is it shared or each object have it's own table.
1- Difference between Array and linked list.
This is second phone interview question it was only one question all the interview.
Given a Binary Tree of int , write 2 function
a) take this BT and return a string.
b) take the string generated and then construct the binary tree from this string
the constructed BT should be the same as the given one in the final.
go through it finished 70% , the interviewer always ask to submit what you have now in an email . finally he requested to send the final code to his email and asked me If I have any questions , that is it . Tell him the truth if you have work you don't have to submit it in the next hour , I requested to submit the code in 4 hours , cause I have work.
Given a number N, print all the ways (combinations) to represent the number from the given set of integers.
Ex: Given set is {2,3,7,8,9} and given number N = 7, then the combinations are:
7,2+2+3. Repetitions are not allowed, hence 3+2+2 or 2+3+2 are not allowed.
Write a data structure to count number of connections on web server in last 1 minute.
How to find the median from a randomly generated 1 billion integers?
Hint: To think of using specific data structure or approach so that the entire integer need not be sorted (to identity integer such that half the integers fall to the left and other half fall to the right of it)
Given two unsorted int arrays, find the kth element in the merged, sorted array.
example:
int[] a= [3 1 7]
int[] b = [4 9]
k: 3
return 4.
How inner classes are useful in our project??
Question: Design a component that implements the following functionality..
1) Record an Event (For the sake of simplicity, treat the Event as an integer code)
2) Return the number of Events recorded in the last one minute.
3) Return the number of Events recorded in the last one hour.
i.e implement the following interface
- Design the interface first
- Give the implementation detail.
<<>>
Open ended question:
What if there isn't enough storage available to store each individual event ?
Design a system to calculate the number of unique words in a file..
1) What if the file is huge ? (i.e cannot fit in the main memory)
2) Assuming that you have more than one computers available, how can you distribute the problem ?
Given a set of words in a dictionary, write a program to group all words which are anagrams of each other in to sets.
You can use any C++ STLs or other languages like python if you want to code this..
example:
input:
"bat", "tar", "xyz" , "tab", "tar"
output:
[["bat", tab"], ["tar", rat"],"xyz" ]
(Note: In this example, all words are only of three characters but this is not always guaranteed. The input may contain words with any number of characters)
Implement the function
char* strstr(char* p, char*q)
which returns the pointer to the first occurence of the string q within string p. (Return NULL if either p or q is NULL or if q does not exist in p).
Implement the function
int pow (int a, int b)
that takes two integers 'a' and 'b' and returns a^b (i.e 'a' raised to the power 'b')
1) Do it using as few multiplication operations as possible.
) If you have class B which inherits from class A, the two values printed below might be different. Why?
B *myPointer = new B();
A *myOtherPointer = myPointer;
printf(“%x”, myPointer);
printf(“%x”, myOtherPointer);
Why doesn’t this work?
#include <iostream>
#include <string.h>
using namespace std;
void newBuffer(char* outBuffer, size_t sz) {
outBuffer = new char[sz];
}
int main(void) {
const char* kung = "KUNG";
char* foo;
size_t len = strlen(kung);
newBuffer(foo, len);
memset(foo, 0, len+1);
strncpy(foo, kung, len);
cout << foo << endl;
return 0;
}
Given a two balanced binary search trees.Merge both the trees so that it will form again a balanced binary search tree.
(NOTE: Request for correction: should the input bst s have same number of nodes? if the input bst s have unequal nodes, we cant necessarily build a balanced bst for the result )
Longest palindrome of the string
Find the Diameter of the tree.
ZigZag tree traversal
Design WorkFlow system . ( Even after the interview I am not sure what he meant so dont ask me to elaborate this. ;) )
Suppose there are 2 persons A and B on FB . A should be able to view the pictures of B only if either A is friend of B or A and B have at least one common friend . The interviewer discussed it for nearly 30 minutes . The discussion mainly included following points -
1. How are you going to store the list of friends for a given user ?
2. File system vs DB
3. Given list of friends of 2 users , how are you going to find common friends ?
4. If you are going to store the friends in DB then how will the table look like ?
5. How many servers do you need ?
6. How are you going to allocate work to servers ?
7. How many copies of data will you need ?
8. What problems will you face if you are maintaining multiple copies of data.
Given a credit card number with a certain number of fixed digits and a certain number of digit placeholders, find the number of solutions such that the entire number yields a remainder of 3 when divided by 13. Use properties of modulus
Given that you now have 2 geographically separated datacenters and a request comes in for a url that's not present in your current datacentre, how will you handle it?
Design a site similar to tinyurl.com
Given 3 input strings S1, S2, S3 for example take s1 = "hard" s2 = "work", s3 = "success"
assign numeric values (0-9) to each of the characters in these strings such that equation s1 + s2 = s3 holds true. Constraints are that all occurrence of a letter should be assigned the same digit. Return -1 if not possible. I told the algo using backtracking but he required in polynomial time for which I had no idea.
. Given a 3D matrix of m*n*o dimension and there lies a cubicle in each cell of the matrix. Assume K cubicle are occupied(you know the coordinates of occupied cubicles) and remaining are vacant. You have to arrange a meeting. So find a cubicle such that the sum of the distances traveled by all the persons should be minimum. A Person can't move diagonally, they can only parallel to axes
1. You are given the ‘downloads’ folder on a computer which may contain a number of files that are duplicates of each other. (these files are the same byte-wise but may have diff names) describe a method which identifies all duplicates in the least amount of time.
2. Now there are k computers each with 1000000 files. You need to determine efficiently the duplicates across all these computers. State the assumptions in terms of topology, connecting device etc.
Suggest methods to identify spam mails
You have to send a file from one computer to k others. Provide a mechanism by which this can be done in the smallest time. Provide all details as the of transfer (bitwise, blockwise, entire file at a time etc.). Compute complexity.
In a college, each student can give grace mark to another student (at max to 3 students). However there cannot be a mutual exchange, i.e. if A gives to B then he cannot receive back from B. Find the minimum number of students (n) that must be present for every student to achieve maximum grace marks and also find the number of ways that this can be achieved for n.
2. A line plotter is given which accepts start and end points to be plotted as well as the line colour. What are the factors that affect the time taken to plot the lines? Given a sequence of lines to be plotted give an algorithm that helps you to plot the lines in the least amount of time.
Design Lift System for 75 floor buildings. Every floor equal, how many lifts should there be and where should which lift stop. { he will make you approach this as a problem, think of your targets, think of average people in each floor, average round trip time, and then solution has to be fair to everybody and yet simple not too complicated.
diff b/t interface and abstract class
hash tables
hash map complexity
code to find prime number between 2 elements
A circus is designing a tower routine consisting of people standing atop one another’s
shoulders. For practical and aesthetic reasons, each person must be both shorter and lighter than the person below him or her. Given the heights and weights of each person in the circus, write a method to compute the largest possible number of people
in such a tower.
EXAMPLE:
Input (ht, wt): (65, 100) (70, 150) (56, 90) (75, 190) (60, 95) (68, 110)
Output: The longest tower is length 6 and includes from top to bottom: (56, 90) (60,95) (65,100) (68,110) (70,150) (75,190)
Given a 0/1 matrix A of size n x n, find the row with the maximum number of 0s
Really like the linear solution of this problem. You have an array of 0s and 1s and you want to output all the intervals (i, j) where the number of 0s and numbers of 1s are equal.
Example
pos = 0 1 2 3 4 5 6 7 8
0 1 0 0 1 1 1 1 0
One interval is (0, 1) because there the number of 0 and 1 are equal. There are many other intervals, find all of them in linear time.
A tree is serialized in such a way that all the leaves are market with L and all the other nodes with N. The tree is serialized keeping the order derived by a pre-order traversal. Write an algorithm for reconstructing the tree. Also, suggest a methodology for improving the serialization.
Find top log(n) or top sqt(n) values in an array of integers in less than linear time.
Given an array A of positive integers. Convert it to a sorted array with minimum cost. The only valid operation are:
1) Decrement with cost = 1
2) Delete an element completely from the array with cost = value of element
Design all classes required for a game Cricket?
Given a number N. find all the prime numbers less than N.
I just took my Amazon 1st round of telephonic interview. The interviewer asked me to code something, which I was not confident with coding and I said my coding skills were rusty. I wasn't expecting coding question over telephone. In total he just asked me 4 questions:
-- diff btw linker and loader
-- what all happens in compilation steps
-- imagine we have 100,000 students, and each has some marks. We have to rank students on their marks.
-- an array of n integers. how to find pairs which sum up to k.
He ended my interview in 30 minutes, where the HR said it would last for an hour.
Does it mean that he was disappointed with me and found me hopeless. My communication skills though were bad. I could not express myself properly.
Design Lift System for 75 floor buildings. Every floor equal, how many lifts should there be and where should which lift stop. { he will make you approach this as a problem, think of your targets, think of average people in each floor, average round trip time, and then solution has to be fair to everybody and yet simple not too complicated. }
Make a data structure which is supposed to log number of user requests per second. At any point of time your boss can ask you the number of hits for the last 60 seconds. It can be at any time for example he will say at 71st second that tell me how many hits for past 30 seconds or something, but this window can go maximum upto 60 seconds to in the previous example 11 to 71.
An unbounded byte array contains characters. Each character is 1 or 2 byte long. There are no delimiters between characters. The MSB of 1-byte character would be 0. The MSB of left byte of 2 byte characater would be 1 and MSB of right byte (second) can be either 0 or 1
there are two systems and transfer a data of 1TB. The hardware is best possible available. Tell the conditions which will optimize the data transfer.
Observe that when you cut a character out of a magazine, the character on thereverse side of the page is also removed. Give an algorithm to determine whetheryou can generate a given string by pasting cutouts from a given magazine. Assumethat you are given a function that will identify the character and its position onthe reverse side of the page for any given character position
You are given an array of positive integers. Convert it to a sorted
array with minimum cost. Only valid operation are
1) Decrement -> cost = 1
2) Delete an element completely from the array -> cost = value of
element
We have been given a deck of cards and each combination has a rating eg 3 As is higher than 2 As 1K etc.
Write an algorithm such that the probability of picking 3 or 5 or 7 cards from the deck results in high rating
where would you see yourself 5 years from now?
Why do you want to join BOA?
I had a phone interview at Amazon yesterday and i was asked one question which i think i did not answer satisfactorily.
the question goes like this:
Is having a lot of branches (if conditions) in a code bad?
my answer was that for an if condition a jump statement is introduced in the assembly code and thus the program has to jump from one memory address to another which eats up a lot of cpu cycle. However, the interview didn't seem impressed and end the interview just after 2 mins
WHY???????????
given an array of integers S[], visualize it as a bar graph, with the index i as x coordinate and the S[i] as the y coordinate. and that the bars are shaded. find the largest rectangle, in the shaded bars.
given two arrays A and B.
A has integers unsorted.
B has the same length as A and its values are in the set {-1,0,1}
you have to return an array C with the following processing on A.
if B[i] has 0 then C[i] must have A[i]
if B[i] has -1 then A[i] must be in C within the sub array C[0] - C[i-1] ie. left subarray
if B[i] has 1 then A[i] must be in C within the sub array C[i+1] - C[length(A)] ie right subarray.
if no such solution exists then printf("no solution");
Give an algorithm that determines the number of inversions in any permutation of n elements (stored as an array) in o(n lg n)
what improvements you want to make to google map? how will u make it?
There is an array and the distance between any two consequent elements is one(+1 or -1) and given a number. You have to check whether the number is in array or not with minimum complexity.
how would u find the amount of dynamically allocated memory??
Its good if u write the code..!!!!
How vector has been implemented in STL ?
What is faster normal variable or pointer?
What is the difference between an error and exception?
How vector has been implemented in STL ?
What is faster normal variable or pointer?
What is the difference between an error and exception?
(2^i * 5^j), increment i and j to ensure the output is sorted
eg. 1 2 4 8 10 16 20 25 32 64 100 125 128
If you have a dictionary (sorted list of words) of unknown size and given a function which returns the word in the dictionary at a specified 'i'th location. Suggest an algorithm for finding a word.
I could think of finding the size of dictionary by exponentially getting (2^i)th element (incrementing i each time till the word is lexicographically higher than the given word) and then simply applying binary search from 0 to 2^i.
given an array and find two numbers in the array having difference equal to given number.i am also given that arr is sorted
You have 5 sorted linked lists. Merge them retaining the ascending order.
There is a straight roads with 'n' number of milestones. You are given an array with the distance between all the pairs of milestones in some random order. Find the position of milestones.
Example:
Consider a road with 4 milestones(a,b,c,d) :
a <--- 3Km --->b<--- 5Km --->c<--- 2Km --->d
Distance between a and b = 3
Distance between a and c = 8
Distance between a and d = 10
Distance between b and c = 5
Distance between b and d = 7
Distance between c and d = 2
All the above values are given in a random order say 7, 10, 5, 2, 8, 3.
The output must be 3,5,2 or 2,5,3
We can begin by subtracting the second largest number from the largest number. But still when the number of milestones is high, it gets a bit complex
Given a Sorted array S. You've to return an index i where s[i]=i or -1 if there is no index such.
You've given a stack with the basic operations - push and pop. You've to modify it so that a new operation "getMin" can be supported at O(1) complexity. There is no constraints on memory.
Design a Flight take-off control system
There are two type of flights - Passenger and Cargo
Each type of flight can be SMALL or LARGE.
Problem is to design a take-off control system such that the following precedence is maintained.
1. Passenger > Cargo.
2. If both flights are same type then LARGE > SMALL
3. If both types and sizes are same then flight with longer GroundDuration(i.e ground stay time) has precedence over other flights.
The design and the implementation should be such that the take-off of all flights happen according to the above conditions.
You can concatenate A to A, and search B in the resulted string using an O(n) algorithm, KMP, Boyer Moore.
write a function which takes two parameter as numerator and denominator and returns the string form of (numerator/denominator)..if the fraction is repeating then the repeating no. should be in bracket.
For ex- input: num=13, den=11
output: 1.[18]
Assume always the input will be between integer value 1-1000. Implement a data structure in which
void Insert(int), void Delete(int), boolean IsTher(int), int FindAny()(returns any no. from previous input)..all are of O(1)..may use extra space if required.
There is a linked list whose node has 3 fields, val, next pointer & random pointer...next pointer points to next node in the list and random pointer can point to any node in the list.Write an efficient function which takes such list and returns the copy/clone of that list.
Given two unsigned integers, write an efficient function which returns the no. of bits needs to be flipped of one to generate the other.
There are 'n' sorted linked list with avg. 'k' length, write an efficient function which return the head pointer of a single list which is the combination of all 'n' list and in sorted order.(Avoid using extra space)
Why the files are treated differently from normal data types in every language or why we need streams to read and write from the files.
There's an array in sorted order. But it has been rotated by N positions. The value of N can be anything from 0, and is unknown to us. In this scenario, how will you find a number X efficiently. Give a solution that works for O(n). I suggested for 2 searches of log n. But interviewer wanted more better solution.
Convert a Binary Search Tree into a sorted Linked List. Head of the linked list has to be returned. The node structure used for BST contains an extra pointer *next which is initially pointing to null. The whole process has to happen in space. One or two variables are allowed tho.
How to remove duplicate element from an array in one pass.
In a dimond problem of multiple inheritance if we derive one of the middle base class as private will the problem be solved or we still need to derive them virtually.
Given a list of n objects, write a function that outputs the minimum set of numbers that sum to at least K. (better than NLOGN)
What is the difference between my and local in perl?
Given a number display it in the seven segment display format.
Apptitude Question Paper consisting of 30 questions:
10-->Apptitude
5-->OS
15--->C/C++
1--->question was on programming --->>write a function to convert integer to Hexadecimal number without using printf statement.
Elaborate what will happen in a fuction()-->u have statement char *P="Test";return p;}will execute.
How to find nth node from the last in a linked list.
A system accepts 0-9 as input. Each digit is associated with a number of characters. Such as:
0: a, b, c
1: d, e
2: f
3: g, h
4: i, j, k, l
5: m, n
6: o, p q
7: r
8: s, t
9: u, v, w
Length of input varies. The system outputs all combinations denoted by input. For example, a user inputs 3456, the output will be:
g i m o
g i m p
g i m q
g i n o
g i n p
g i n q
g j m o
g j m p
g j m q
....
Given an array of 2n elements of which n elements are same and the remaining n elements are all different. Write a C program to find out the value which is present n times in the array
Write your own strtok(sting,token) function..O(n^2).
Follow Up
Then write O(n) version of it.. interviewer strictly asked to write O(n)..??
Write a java code to find the second minimum element in an array using single loop.
1) An array contains a set of +ve and –ve numbers. Find the number that is nearest to zero. If two numbers are equally near (like 2 and -2) then return +ve number.
Identify the duplicates from a given array and remove them efficiently
Given a binary tree convert it into double linked list
eg:
A
B C
D E F Goutput should be A B C G F E D or A C B D E F G
Given a postfix expression convert into infix expression.
The input number is n. Find the closest Fibonacci series number i where i < n.
Show the time complexity of the problem.
For eg : if n = 10, the output "i" should be 8
what is the time complexity of finding the number of devisors of a number
There are 4 people in a closed room and you are waiting outside to enter into the room. You can enter only when one of them opens the door. The probability that somebody will open the door is 1/2. Now what is the probability that the door will be opened so that you can go inside?
Here I got one question: Merge two arrays and sort them in order as specified at runtime. The two arrays may share common entries between them, but the resultant array must not have duplicates.
Please define this with space and time complexity.
write you own strncpy function:
char * strncopy(char * dest, const char * src, int n);
Need to consider several boundary cases, like if n > strlen(src) or n > strlen(dest), what if src is NULL)
How to serialize/de-serialize a binary tree?
Given an array A[i..j] find out maximum j-i such that A[i]<a[j] in
O(n) time.
You are given a random function that generates two characters a and b. The probability of getting a is x and that of getting b is 1-x. Write a function that uses this random function and returns a and b with equal probability.
You have a note to write by cutting and pasting necessary letters from the book, write an algorithm to see if you can write the note.
given a number n... print a spiral matrix in O(1) space example if n=5 the op should be:
25 24 23 22 21
10 09 08 07 20
11 02 01 06 19
12 03 04 05 18
13 14 15 16 17
The question may appear trivial but its not...u hav to print in O(1) space
Why manhole make of steel?
Why manhole round?
2. Given a integer array of length 2, the elements may be (0 & 1) or (1 & 0) or (1 & 1 ) convert it to (0 & 0) using only the negation operator.
Given a unsorted array, there is one element where a[i]==i . find the element in logn
Write code to calculate forward, reverse and cross edges of a given graph
How can we sort one unsorted int array with O(n).
Unsorted : {4,2,6,1,5,5,1,2,45,444,44,45,4,1}
Sorted : {1,1,1,2,2,4,4,5,5,6,44,45,45,444}
Imagine there are infinite number of Queens (Chess Game Piece) with u. Find the minimum number of queens required so that every square grid on the chess board is under the attack of a queen. Arrange this minimum no. of Queens on a chess board.
how you will find the lowest common ancestor(LCA) in Binary Tree..its clear its Binary Tree not The4 Binary Search Tree ??
Given An unsorted Array of non-negative integers
1. how many different Binary Tree can be made from this array ??
2. How Many will be unique ??
3. write an algorithm & then code to from
binary tree from this array for explanation reason & reducing the time u can take take the n=4 etc.
This is toughest question i face form amazon i stuck for moment then i explained him too much but didn't seems to be satisfied..
it was asked in problem solving & coding round so we have to write the code after explanation ??
let me know guys how u will do it..??
find the longest repeated substring given an input string. eg. given "banana" you should find "anana"
Was asked abt this on phone screen & was asked to code it in 5-10 mins after being done on phone.
On site : Given a word e.g.'dear' find all the valid anagrams of this word. A valid anagram is a word which exists in the dictionary. Give an optimised solution
Create an address book. Every entry in the book is a contact whose fields are First Name, Last Name, and Phone #. The collection of contacts are organized in alphabetical order of the first-name. How would you go about sorting this list of contacts? What kind of structure would you use to form your collection of contacts?
Write a program which can detect if a linked-list has a cycle in it or not. That is, write a program which can detect if the linked-list is circular or does terminate at some point.
Consider a series in which 8 teams are participating. each team plays twice with all other teams. 4 of them will go to the semi final.How many matches should a team win, so that it will ensure that it will go to semi finals.?
what does *p++ do
Sort 1TB file on machine with 1GB RAM.
Implement function to find needle from a haystack. Interviewer was looking for coding skills.
When Adobe is going to conduct a test in Hyderabad .....
Consider product ratings of amazon. ( these are avg ratings out of 5, say 3 persons gave it rating of 3 4 and 5 ,the avg rating would be 4 ). For given large amount of products you have to find top ten products based on these avg ratings.
Note: The product rating keeps on changing in its life time.
there are 81 horses. you need to select the first best 6 horses. Each time only 9 horses can participate. how many minimum no. of races you require
Given a sorted array find all possible |ai - aj| where ai,aj belongs to Array A. n^2 is obvious. Find a solution in O(N).
Question asked on phone interview at Norvax.
Design the game of Blackjack/21. The pointers he gave me were that I needed a class for cards, deck, players(of which a specific one would be the dealer), a game, a way to keep aggregate scores.
4 people need to cross a bridge.
Person a = 1 min
Person b = 2 min
Person c = 5 min
Person d = 10 min
They have 1 flashlight and need to cross a bridge in the least amount of time. They can only move in pairs.
Static v/s dynamic variables
Display an integer array of [1, 2, 3, 4, 5, 6, 7] in the following format
1 4 6
2 5 7
3
The method signature takes in an array of integers and the number of columns. In the above example, noOfCols = 3. The columns should contain equal number of elements as much as possible.
Given a set of numbers eg:{2,3,6,7,8} . any one who is playing the game can score points only from this set using the numbers in that set. given a number, print all the possible ways of scoring that many points. Repetition of combinations are not allowed.
eg:
1. 6 points can be scored as
6
3+3
2+2+2
2. 7 can be scored as
7
2+2+3
but 2+3+2 and 3+2+2 is not allowed as they are repetitions of 2+2+3
Given an n-ary tree find out whether given element is there in the tree or not without using recursion
In our indexes, we have millions of URLs each of which has a link to the
page content, now, suppose a user type a query with wild cards *, which
represent 0 or multiple occcurrences of any characters, how to build the
index such that such a type of query can be executed efficiently and the
contents of all correpsonding URLs can be displayed to the users? For
example, given a query http://www.*o*ve*ou.com. You man need to find iloveyou.com, itveabcu.com, etc.
Design a jigsaw puzzle?
can you call one constructor from another in c++?
2.Explain System.out.println("Hello.");
----what is System?
----what is out?
----what is println?
how all they work.
1.Can we use throws along with tr/catch blocks or not?
Write a function which takes two arrays of equal size as input and makes averages of those two arrays equal.Or rather sum equal
How to check a tree is balanced? what if it is not BST?
Given an N arrays of size K each.. each of these K elements in the N
arrays are sorted, each of these N*K elements are unique. Choose a
single element from each of the N arrays, from the chosen subset of N
elements. Subtract the minimum and maximum element. Now, this
difference should be least possible minimum.. Hope the problem is
clear :) :)
Sample:
N=3, K=3
N=1 : 6, 16, 67
N=2 : 11,17,68
N=3 : 10, 15, 100
here if 16, 17, 15 are chosen.. we get the minimum difference as
17-15=2.
Find a element in binary tree?
It was for the preliminary phone interview question.
Find the shortest distance between two nodes in a binary tree.
My answer has two other helper functions to make it clean.
The first function is node* GetCommonDenomination( node* root, node* n1, node* 2) and the second function is int GetDist( node* hd, node* nde)
First I got the common denominator between two nodes and add the distances between commondenominator to node1 and commondenominator to node2.
The interviewer asked me if there is anything to improve and possible error cases. I thought that I gave him the complete answer for the question but they didn't call me for the followup.
What do you think of the problem? Can you guys think of any better answer for that?
When is a template a better solution than a base class?
Hello
Suppose I have set of files and in every files there are include# to other files in the same set.Suppose I have function that load all the includes in certain file.I need to write function that load all the includes in some given source file so I will avoid infinite loop and circular call for the include.
To solve the question I have to use this function i can't use pragma once or something similar I think it could be solved by recursion though I am not sure how
Thank you
There is an Array with positive and negative integers randomly distributed. find the maximum sum of a subset of this array. (subset could contain any number of elements but not the adjacent elements). Follow up, what is the complexity of your algo.
You can use additional Datastructures if you want.
There is a linkedlist. Each node in the linked list has a pointer to next and some arbitary.
normal next 1-->2-->3-->4-->5-->6
arbitrary links 1-->3-->6-->2-->5-->4
something like above. Make a copy of this linked list. Follow up what is the complexity (time,space) the complexity (time,space)
There are N stones in front of you. You and your opponent have to play a game. Anyone who plays next can take 1 or 2 stones from the pile of stones and leave the rest of the pile to be taken by the next guy. Whoever picks the last stone wins according to the rule. You are allowed to choose whether you should start the game or the other guy should start. How will you make a winning strategy out of it such that you always win the game.
Design a system that manages the inflow/outflow of the messages in an email.
You have a list of jobs that need to be scheduled. For each job, you know when it should start and when it should end. You need to come up with an algorithm to schedule the maximum number of jobs possible.
Simulate Friend recommendation system in a social network. Propose various heuristics for the same and how will you manage the tables.
You are given an array of size n (may be a stream also). You have a sliding window of size k. The window first boxes the first k elements of the array and slides slowly over the array by shifting its position 1 element each time. At each position of the array, you need to find the minimum element in the sliding window. i.e. you need to give the minimum of 0 to k-1 elements, then 1 to k elements, 2 to k+1 elements etc. So if your array's size is n, you have to give me n-k+1 minimum values.
E.g. Assume that the array is 5,1,3,2,6,8,4,6, and the window size is 3
You should give me 1,1,2,2,4,4. How will you give it?
You are given a large string. You need to cut the string into chunks such that each substring that you get is a palindrome. Remember that each 1 length string is always a palindrome. You need to find the minimum number of cuts that you need to make such that each substring is a palindrome.
Write algorithms to implement the following operations on a stack
pop
what is the difference between
T *o = new T
and
T *o = new T()suppose You have a billion urls, where each is a huge page. How do you
detect the duplicate documents?
on what criteria you will detect it, what algorithm , approach ,
whats will be the complexity of each approach
as it has many application in computer science ...
A good discussion on this topic
how do we return value from a function from a recursive function and we should be able to return value as soon as particular value is encountered
how to print out the nodes of link list that has loop in it ?
Given an array of elements and a value.....see that the sum of two elements of an array are equal to the value with minimum loop
Design a parking lot class.
Write a java program which will return word equivalent of a number. For example if input is 101, it should return "One hundred and one"
What is "Final" and "finally" in Java ?
F2F 4 - Code and Design : implement bounded LRUcache
F2F 3 - Code : roman numeral to integer, assume valid roman input string (I,V,X etc)
Code : find unique elements and number of times they are occurring in an array of integers
F2F 2 - Code : nth prime number
Design : find top k, n page sequence visited by logged user from server log data file containing fields UID, timestamp and URLs
F2F 1 - Code : 2nd largest element in a binary search tree
Design : Vending machine
Alogorithm:
Perform the inorder traversal and then the second element from the last will be 2nd largest element.
Phone 2 - Code : Given array and elements that are occurring even number of times and one occurring odd number of times, find number occurring odd.
Follow-up - Code : write algo other than XOR
Phone 1 - Code : Array of integers and target number, find if sum of any two numbers in the array is the target. Followup - assume numbers in array are not unique
Design : Game of Chess
Given an array of ints, is it possible to divide the ints into two groups, so that the sums of the two groups are the same. Every int must be in one group or the other. Write a recursive helper method that takes whatever arguments you like, and make the initial call to your recursive helper from splitArray(). (No loops needed.)
splitArray({2, 2}) → true
splitArray({2, 3}) → false
splitArray({5, 2, 3}) → true
Design parking lot management system.
Given a sorted array and a number n.How can u find the number of occurance of n in the array . should be o(logn)
Give a non recursive algorithm that performs an inorder traversal without using a stack or any extra space.
How do you partition an array into 2 parts such that the two parts have equal average?...each partition may contain elements that are non-contiguous in the array....
(3rd phone interview)Design Clothing store using OOP concepts. based on your design tell how you'll find if the store has XXL size of a particular shirt.
(3rd phone interview)functions to print first n odd powers of 3, where n is given to the function:
void power(int n)
{
if(n<=0)
throw IllegalArgumentexception
else
{
for(i=1;i<n;i++)
int result = Math.pow(3, 2i-1);
System.out.println(result);
}
}Plumber
Contractor
SubContractor
House Owner
Who's the customer here?
Game Developer
Dev manager
Parent
Child
Who's the customer here?
List all sort algorithms you know. Their best, worst, average case complexities.
Design distributed Cache
Design Restaurant Reservation System
Implement function to return minValue from binary tree
Implement Iterator on Binary Tree that iterates through leaf nodes left to right
You are given two 32-bit numbers, N and M, and two bit positions, i and j. Write a method to set all bits between i and j in N equal to M (e.g., M becomes a substring of N located at i and starting at j).
EXAMPLE:
Input: N = 10000000000, M = 10101, i = 2, j = 6
Output: N = 10001010100
_
________________________________________________________________
WRite a function to find log() using sqrt() function
Given a set of words, group all the anagrams groupwise.
Implement a recursive java method for listing all the files and directory from an input file.
Implement Cache management in Java.
question on analyzing a piece of code and then asked about what can go wrong in this code like what exceptions can occur/what the code is doing.The question was extended to involve issues related to threads.
Create a arraylist and retrieve specific element from an arraylist. (You can create arraylist only by using stacks)
OS questions like file system with some specifics into Unix FS, memory management.
generic questions about implementation of malloc()
Design a distributed system for storing a static set of (key,value) pairs and should serve user-queries(users provide a key, and system should return a the value).
This was a system design question where I was supposed to find the number of m/cs required, networking between them, hard disks, distributing the values across them, identify bottlenecks, replication, reliability, estimation of response time, throughput etc.
For designing the system, he gave me set of resources, like configuration of the machines available, Ethernet cable B/w, etc
Write a program to print a 2-D array spirally- i.e, starting at a corner and spiraling inwards.
Reverse the bits of an integer
You are getting a number of two-tuple values <time, val>, where time is non-decreasing. Then a query asks for the value at a particular time. If a tuple exists for that time, it returns the val. Otherwise it returns val from the tuple that is the closest successor to the query time.e.g.
<1,3>, <8,6>, <10, 11>, <19, 4>, <23, 9>,...
Q = 6? Val = 6.
Q = 10? Val = 11.
OOD , you are designing Stress class that test fire and weight on furniture , you have Furniture base class , and wood_chair ,steel_chair , wood_table , steel_table , sub classes , redesign this to be more flexible? what I did I just make another base class Material that had getMaterial() and the Furniture class had attribute material (composition) , so you can add Materials ass you want(plastic, steel ,wood) and ovveride get material to return the correct type , and from Furniture you can drive whatever furniture you want and then set matrial , so you can Iterate through them with common interface , I also designed a strategy pattern to return the correct algorithm for the furniture and material you can add a Factory pattern also but he was very satisfied .
classical anagram question , list of static words given a word check if it anagram or not ? this is repeated and simple. *also Asked given a BST find the second largest element , be careful with special cases like the tree is not balanced , the tree all node in the left and you will be able to get it easy.
Design your hash_map that allow the following Add in O(1) , delete in O(1) , iterate in O(n)? what you need to iterate in O(n) where n is the number of existing element , empty slot in hash_map don't count , simple example is yu have 10 element in 10,000 slot hash_map you need to itrate in O(10) ,? so what I did , is link the value as linked list beside the normal hash functions , so you have class Node{public:int value;int key; Node* up; Node* down;} , and when you insert normally myvector[hash(node.value)]=node; after that link the node and have tail and head , and ake care of cases when you inserting between nodes and deleting the tail , and so on
Write an algorithm to check if an array holds a string value that you are passing in
There is a class A which contains just one parameterized constructor A(int a).
How would you initialize an array of objects of this class.
What are the different types of cast in C++? Difference between static, dynamic, reinterpret cast.
There is an array a[10] which contains 1's and 0's. Write a program to have all 1's in the start of the array and then the 0's.
The complexity should be O(n/2).
Detect loop in a linked list. What is its complexity. Optimize it to O(n).
Difference between pointer and reference. Can a NULL pointer be used as a reference?
You have a Word Processor type Program. There are 2^16 fonts. Each font is associated with a 4MB geometric instruction set. This is written in a flat file.
Everytime a user selects a font this file is searched linearly. Develop a program to optimize the font search. (You could either add some functionality improvement in the word processor application while font selection or in the font search file).
Write test cases for on-line money transfer in a bank.
Write test cases for testing a installer. (eg: Firefox installer )
Write a program to count the number of vowels in a string.
Write test data for a program which returns the third largest number in a given array.
Write a program to ensure given String is well formed or not. The string contains both opening (eg: {,[, ( ) and closing ( eg: }, ]. )) braces. Well formed means open braces should have corresponding closing braces. It can come nested.
Ans : Use Stack to keep track of this. When ever you get a open brace push to stack. when ever you get a closing brace pop the top from stack and match whether it is proper brace.
Explain the QA process in your organization
You have installed a program in your PC. Its not working. How to debug?
Write a program to get the sum of digits in a number till it become a single digit.
eg: 789 --> 7+8+9 = 24 ---> 2+4 = 6
Write testcases for cart in a online shopping site.
A MxN matrix is given. All rows and columns are sorted in ascending order. Search for a given number in this matrix efficiently.
There are 25 horses and only 5 race tracks. Need to find the fastest horse among them in minimum trials. You dont have any stop watch. Find second fastest also.
1. Write program to find the number of given sub-string in a string ?
Find whether given binary tree T1 is subtree of binary tree T2 ? duplicates are allowed in both the tree nodes.
Given a building of H number of floors and an elevator composed of N boxes such that only one box stops at a particular floor and that if a box stops at x-th floor than the box on top of that would stop at (x+d)-th floor for some constant d.
Given H and N, find the number of different elevator configurations. Two elevators are different if their bottommost box is at first floor than there exits an "i" such that a box is at i-th floor in one elevator and no box is at i-th floor in other elevator.
For example,
if H = 9 and N = 3,
then there are 2 configurations possible.
1) First box stops at 1-st,2nd,3rd floor. Second box stops at 4-th,5th,6th floor and third box stops at 7th, 8th, 9th floor.
2) First box stops at 1st,4th, 7th floor. Second box at 2nd,5th,8th floor and third box at 3rd, 6th, 9th floor.
How would you design transfer of data packets from NY to Tokio?
First I thought of traveling salesman problem where weight of connections between nodes is throughput of network. This problem is NP which lead just to interviewers reply that I should care about design of system, recovery of data and acknowledge whether data has been transferred.
Implement a Memory Pool using ByteBuffer.
operations: public ByteBuffer allocate(int size) // Creates and returns memory of size 'size' from Memory pool
public ByteBuffer free(ByteBuffer buffer) // frees ByteBuffer referred by buffer from Memory Pool
Implement various operations of a double ended queue (Deque).
Deque is a data structure where items can be inserted and removed from both ends.
Operations :- insertToLeft(), removeFromLeft(), insertToRight(),removeFromRight().
Design a online Auction system (similar to e-bay)
Functionalities include enlisting a product for auction by bid owner, Placing bid for a product by bidders,Bid winner selection,Notification of bid winner etc ). Interviewer was mainly looking for Objects involved in the system and their relationship and use of design patterns
Find the mid of linked list. Sometimes it’s not returning the mid what can be issue. If this class is accessing by multiple threads how to avoid that. If we use Synchronize the performance will be reduced how to tackle that. This class has some other methods as well like addNode, deleteNode, findNode etc.
. we have an array of length 1…n and every elements can contain number between 1 to 50. Find out the occurrence of every number and one can not use any other data structure or extra memory.
You have an input file which has one word per line. Write a java
program which takes this input file and produces an output file satisfying
the following conditions:
a. Each line of output file should have 1 word
b. Output file should contain input file words sorted by frequency
i.e. most frequent words appear at the top and least frequent words at
the bottom
c. For two words having same frequency in the input file, they should
appear sorted alphabetically. for e.g. if A appears thrice and B
appears thrice in input file, output file should have A appearing on
three lines and then B appearing on three lines
d. If an input word is repeated X times, it should appear on X lines
in the output file.
Sample input/output file are as follows:
Input Output
Dog Abhishek
Amar Abhishek
Abhishek Abhishek
Abhishek Amar
Amar Amar
Abhishek Amar
Amar Dog
Boy Dog
Ball Ball
Dog Boy
Algorithms - insertion into a sorted linked list, reader writer problem (pref to writers), Dijkstra, MST
Data structure - to implement a phone book
Many c++ questions - Virtual destructors, Multimap, how to identify memory leak
How to identify deadlocks, When should we use multi threading, what is virtualization
Write a function
int triangle(const vector<int> &A);
that given a zero-indexed array A consisting of N integers returns 1 if there exists a triple (P, Q, R) such that $0 \leq P < Q < R < N$ and
A[P] + A[Q] > A[R],
A[Q] + A[R] > A[P],
A[R] + A[P] > A[Q].
The function should return 0 if such triple does not exist. Assume that $0 \leq N \leq 100,000$. Assume that each element of the array is an integer in range [-1,000,000..1,000,000].
For example, given array A such that
A[0]=10, A[1]=2, A[2]=5, A[3]=1, A[4]=8, A[5]=20
the function should return 1, because the triple (0, 2, 4) fulfills all of the required conditions.
For array A such that
A[0]=10, A[1]=50, A[2]=5, A[3]=1
the function should return 0
I recently attended an interview of this company.
I was given a problem & I was asked to come out with an approach to solve this problem. I failed to answer, but I wish to know your idea.
The problem is :
You are given 3 machines with same database schema. All the data in these 3 machines are to be copied to a master database.
I was not given any more inputs.
Can anyone share any idea about the approach?
TIA
malloc(0)
Given a set, write a code to create a power set.
Eg: Set = {1,2}
Power Set - List containing sets {1},{1,2}, {2}, { }
A sample programme:
package misc;
public class PowerSet {
private void printPowerSet(String inputString, String prefixString, int startIndex){
if(inputString == null){
return;
}
for(int i=startIndex;i<inputString.length(); i++){
String str = "";
str = prefixString + inputString.charAt(i);
System.out.println("{" + str + "}\n");
printPowerSet(inputString, str, i+1);
}
}
public static void main(String args[]){
String inputStr ="123";
System.out.println("{ }\n");
for(int i=0; i<inputStr.length(); i++){
PowerSet powerSet = new PowerSet();
System.out.println("{" + inputStr.charAt(i) + "}\n");
powerSet.printPowerSet(inputStr, Character.toString(inputStr.charAt(i)), i+1);
}
}
}Implement the bucket tool in MS paint. Bucket tool is the one which fill colors when we click at any point. You get an input of x n y co-ordinates and the new color to put.
Get the max sum if you are given a chance to go first.
You have a list of coins, Example {12, 24, 10, 5}
You can only pick the end coins, either 12 or 5 in the fist pass and so on.
reverse every 3 nodes of a linked list
Write an algo to find the maximum distance between two nodes in a BT
Write a code to spiral up in a 2x2 matrix
Implement a program to represent the all cards of a playing card game. Also write some functions to shuffle it. Also one function to give cards if user asks. Give all implementation details and data structures.
You are given an array of numbers and another number k. You have to find out two numbers in the array which add up to k.
generate all possible combination of balanced parentheses for a given value
shufflemerge two linked list.
L1: 1->2->3
L2: 4->5->6->
output: 1-.4->2->5->3->6->7
What's the complexity of the following code?
int fib(int n){
if(n==0||n==1){
return 1;
}
return fib(n-1)+fib(n-2);
}
i have been told to draw binary tree
*
/ \
- +
/ \ / \
2 3 4 5
print out this as (2-3)*(4+5).
i explain to traverse tree using recursive method in inorder. and he streatch q furthre in runtime and than asked to do without recursive.
Best way is using Eulers way.
i have been told to explain diff datastructure than discuss best way to insert and retrive in constant time.
at that time i told about hashmap and he was sattisfied.
i have been asked for very common question of finding from files under directory which contains phone number.
answer is grep. if u dont know regex its fine.
Write test cases for
delete numbers found in list2 from list1 and returns new list1 length?
int deleteDuplicates(int *list1, int length1, int *list2, int length2)
Write test cases for
int divide(int a, int b)
you have to use subtract to get the result!
When implementing >ls a/b/c/./e/../f/./../g/./../h in Java, what data structure will you use for storing a/b/c/./e/../f/./../g/./../h?
How would you implement the "ls" in Java. It should take the input:
>ls a/b/c/./e/../f/./../g/./../h
and the output should be similar the the output given by unix.
What does the following command do in unix:
>ls a/b/c/./e/../f/./../g/./../h
Consider a,b,c....g,h to be folders
Given a Integer Array of length N, find the absolute difference of every pair of elements in the array.
Do it faster than O(N^2)
Find the oldest customer in your database
You have a folder which has many sub folders, which has many sub folder and it goes on till you find a sub folder having a file which contains a phone number. Identify the file
Print out all prime numbers from 1 to n..
We have an array or ArrayList which contains int numbers. Check to see the sum of any two elements is same as given target.
{ 1,2,13,7,34,24,9,3....}
We need to find that sum of two number is suppose 11 and return index number for them....all possible combinations. In java
m x n integer array, 0 or 1, given a src and dest cell, find the number of all paths from src to dst with all '0' cell visited once, the cell with value '1' can not be visited.
you can move up, down, left, right
e,g,
s 0 0 s -> 0 -> 0 or s 0 -> 0
| | ^ |
0 0 0 0 <- 0 <- 0 0 0 0
| | ^ |
0 0 d 0 -> 0 -> d 0 -> 0 d total 2s 0 0
0 1 0
0 0 d total paths 0
a) There is a square of nxn size which is comprised of n-square 1x1 squares. Some of these 1x1 squares are colored. Find the biggest subsquare which is not colored.
b) Also asked to extend it to find the biggest area rectangle.
You have n1 items of size s1, n2 items of size s2, and n3 items of size s3. You'd like to pack all of these items into bins each of capacity C, such that the total number of bins used is minimized.
How can we achieve a solution using minimum number of bins? Greedy isn't surely working.
Can anybody suggest what subproblem should I create for dynamic programming solution?
Write a program to convert binary tree in to doubly linked list such that doubly linked list represents the spiral order of given tree using recursion, Inplace(no Extra Space except recursion memory stack)
given pointer to head of binary tree
1
/ \
2 3
/ \ / \
4 5 6 7
doubly linked list represent
head-> 1 2 3 7 6 5 4
Also asked me about my most interesting project and wanted to know what I did in that.
A functions inputs an array and gives out a shuffled version of the input array. The technique he described is to generate random value between 0 and n-1 and append the particular value from the input list to the output list. He wanted me to give a correct way of doing this.
How do you get two numbers that sum up to x from an array of n numbers in the shortest time.
Asked me about Has tables and complexities of various operations on it.
Asked me basic questions about data structures. Also asked me to give a detailed explanation of Heaps. How to add, delete nodes.
How will you design a ticTactoe game using a 2-D array.
how will you design google instant search? (suggestions when you type letters)
A class inherits Thread. All the methods are synchronized. If two objects are created then which one will get access to the class first?
Can you predict the order? why, why not? Explain wrt thread model.
Why is it fine to alter the data members' value of a final class?
Write insert function for a binary search tree?
Given constraint:
1. The insertion should be such that the tree remains balanced.
2. You can move the any non-leaf/root node to be a leaf/non-root node.
At the end of inserting any random insertion the tree should be BST and balanced. he gave the sample data as {1,2,3,4,5,6,7,8}
void fun(int *p){ int v = 0; p=&v;v++;}
int main()
{
int* p;
fun(p);
}
what will be the output. One of the options was compiler error which is the right one as tested by me.
Design a reference counted smart pointer.
Design a data structure which should behave LIKE a queue. FCFS should be followed.
Name = SQueue.
3 Operations -
1) Enqueue - Put the items at the end of the queue.
2) Dequeue - Remove n return the element at the head of the queue.
3) FindMe - Return the smallest integer in the queue currently.
The challenge is to support all three operation in O(1) Amortized Case Complexity.
You have a sorted array.
It is then rotated left/right i times.
eg.
1 2 3 4 5 6 7 8 9
Rotate it right 3 times.
7 8 9 1 2 3 4 5 6
You are just given the rotated array. Nothing else.
Design a searching algorithm which find a position of the provided key in O(log n) time.
Given a binary tree.
It might be full or some nodes might be missing.
Every node has a extra "next" pointer.
Make the "next" pointer point to the next cousin/sibling node. Last node's "next" pointer should point to null.
Eg.
Given Binary Tree -
1
2 3
4 5 6 7
8 9 10 12 13 14 15
1's next = null
2's next = 3
3's next = null
4's next = 5
5's next = 6
6's next = 7
7's next = null
8's next = 9
9's next = 10
10's next = 12
12's next = 13
13's next = 14
14's next = 15
15's next = nullYou have a stream of 1 million numbers.
They are not in memory, you are reading them from a stream.
You have to give top 'K' biggest numbers.
Give a solution better than O(Kn)
Spiral Print a binary tree.
Binary Tree might be full or some nodes might be missing.
Eg.
Given Binary Tree -
1
2 3
4 5 6 7
8 9 10 11 12 13 14 15
Print
1 3 2 4 5 6 7 15 14 13 12 11 10 9 8Solution:
1) Initialise two queue queue1 and One Stack stack1
2) Consider root element at level 1
3) Put root element in queue
4) while(stack1!=null || queue1 !=null)
4.1) if(level ==odd)
while(queue !=null)
pick first element from queue and process it
put all the childs of picked element into stack. If level is odd then first put left child and then right child.
4.2) if(level ==even)
while(stack !=null)
pick pop element from stack and process it
put all the childs of picked element into queue. If level is even then first put right child and then left child.
5) Increment level by 1
Given 2 sorted integer arrays, find the intersecting element in them.
Given 2 sorted linked lists - merge them. Make sure you don't have duplicates in the merged list. The input lists could have duplicates within them or across the 2 lists.
printing, deleting linked list and some more questions on linked list, accesing time of binary search
implementation of sizeof(), string copy, macro defintion, testing no.of bits set in a number, dynamic allocation of double array, structure padding
what classes can i make in UML program for parking garage project in software engineering
Formatting was incorrect so posted again.
Consider the given structure:
struct node
{
int data;
struct node *next;
struct node *next_larger;
}
You are given a list where each node is of type defined above. Initially all the next larger pointer of each node points to NULL. Write an algorithm to update the next larger pointer of each so that they point to immediate next largest node in the list.
e.g.
4-------->8------->2------->1------->9
|->NULL |->NULL |->NULL |->NULL |->NULL
Output:
|------------------|
V |--------!-----------------V
4-------->8------->2------->1------->9
|---------^ ^--------| |--->NULL1st Round interview:
Command to sort the file contents in Linux
Written round pattern:
15 Question - Aptitude
15 Question - SQL / JAVA / C++ (any 2 sections, objective)
Subjective:
SQL - School, Courses & Teachers scenario. Asked to write 3 queries.
These queries where slightly complicated as they all required use of Inner Query / JOINS
JAVA - Write a program to simulate the digital display (as in Calculator)
C++ - Implement a generic smart pointer with reference counting.
C++ objective was heavy on operator overloading.
SQL objective was no cakewalk either.
Aptitude is a compulsory section and questions were of moderate difficulty (Ratios, Work and Time, SI, CI, Probablity, Permutation, Circles etc)
1st Round interview:
Asked to write a query which would join 3 tables to query for rows.
1st Round interview:
Content Based Search (Have a file with a word say "Mumbai". Do not remember the File Name or the File Path. Search for the string)
1st Round interview:
Stored Proc vs Normal Query. Which is faster and why?
what kind of bug have you found in your job and why was it so big?
There was no code related question at all. no questions on resume.
what kind of tests will you do?
what will be your scope of testing, what will you automate and what will remain manual
webservices related.(round 1 interview)
Write all test cases for a system where the user who is already a member at amazon wants to register as a new user for kindle. where will the password will be stored? how will you test the login aspect (user id and password as its using from existing account)
Don't remember the exact question but it was essentially to simulate multiple inheritance in java.
Describe and test the function that returns the angle between minutes and hour hands in a clock. What corner cases would you test?
Design OOP constructs for the following functinoarlity. There are multiple types of phones (android, iphone etc). Each phone has a subset of features (voice, text, etc). How would you write the classes and inheritance esp. in C++?
What data structure would you use to implement spell correction in a document. The goal is to find if a given word typed by the user is in the dictionary or not (no need to correct it).
What is the complexity? What if you have to support multiple languages/dictionaries?
Given a matrix of 1s and 0s. Implement an algorithm that sets all cells of row i and column j to 0 if the original matrix has a 0 in cell (i,j). Would the algo change if you have to set it to 1 instead of 0?
Leader election algorithm in a distributed system.
Describe how to get the top k queries from a search log of terabytes of data. Memory/Disk per machine is limited but you can use multiple machines.
What is the time and space complexity of Fibonacci series recursive function.
Efficient way to count number of 1s in the binary representation of a number. How can you do it in O(1) if you have enough memory to play with.
Re-arrange an array containing only 0s,1s and 2s, so that all 1s follow all 0s and all 2s follow 1s. e.g. 00000011111111222222. Linear time algorithm.
Clone a connected undirected graph. Input is a node*. Return the node* of the cloned graph.
struct node
{
int value;
vector<Node*> neighbors;
}
Implement strstr function without using any library functions.
Count words in a sentence. Words can be separated by more than one space.
Print a binary tree in level order with a new line after every level.
There is an input message queue where you can read from, the message contains an alphanumeric key value. There are also three output message queues that you can write into.
You need to get each message from the input queue and put it into one of the output queues. There could be duplicate key values coming out of the input queue and once we put a key value say "ABC1234" to output queue-1, whenever we get a keyvalue ABC1234 it should go to queue-1 only. Also we should try to balance the load among the 3 output queues.
Design an alogrithm for it.
Suppose we can compare two arrays like:
{4,2,3} > {3,5,6}
{4,2,3} < {4,3,0}
In each move, you can only switch a number with one of its neighbor. Given an array and a number n, design an algorithm to make this array maximum using n moves. (needs clarification)
I applied for the Pricing Quant Internship in Bloomberg and gave the Online Assessment test. I prepared for the Finance and C++ questions but to my very surprise they were all analytical for which I never prepared. Guys if you have applied for the same position please do CAT questions and Reading comprehension.
you are given two arrays. A of size n, B of size m. m is a very very small number compared to n. find out if A contains a substring which is anagram of B.
Suppose you are given a cube and each face of the cube contains an array of size N X N. You need to print the entries of this cube in a SPIRAL ORDER.
1) How would you define a spiral in above case such that there is no collision between each layer of the Spiral?
2)How will you store the above structure i.e. cube?
3) Write the code for the same.
PS: I was only given 20-25 minutes to solve above questions.
There is an array of size 50 that is expected to contain all the numbers from 1 to 50 (every number occuring only once). But there is one number in the array that doesnot satisfy this condition i.e. one number is either duplicate or outside 1 to 50 range. Find the correct number that is missing in the array.. O(n) soln required.
he drew a diagram on the white board, asked me this synchronization problem abt 2 processes trying to communicate with the hardware. there was 1 bit register on the hardware u can use as extra memory if u want. there were several approaches i tried, some which wouldnt work, the rest im not sure if they were right. in the end he said now give me a solution if it were a multi processor system. i didnt really say much after that. was pretty stuck.
example of volatile usage.
aligned malloc, asked me exactly y do u allocate extra space for the void *. i tried to explain why, he wasnt listening. in the end he told me what i was trying to tell him
os concepts involving deadlocks, semaphores, spinlocks, sleeping in the kernel ( process and interrupt context ), softirq's
interrupts, interrupt handling, few virtual memory questions
find if 2 strings are anagrams of each other
implement c subtring function. write the code, along with error checks and some basic testing
rotate a matrix by 180 degrees. mxn matrix
strucure padding, why network packets are not padded, how to avoid padding ( i told him the __attribute(packed)__ pragma )
implementation of the sizeof operator, i told him its an operator, he said no. he wanted me to write the code how it works.
angle between hands of the clock.. the interviewer was expecting me to have a formula memorized. i told him i dont know any formula so i derived an equation which worked. he was still very skeptical abt it, until i did some testing n showed him it works.
delete a particular node in a linked list given a pointer to that node, what if it was the last node
Problem Statement
Given a list of integers, find the n-th smallest number, i.e., the number that appears at index n (0-based) when they are sorted in non-descending order. The numbers will be given in intervals. For example, the intervals (1, 3) and (5, 7) represent the list of numbers { 1, 2, 3, 5, 6, 7 }. A number may be present in more than one interval, and it appears in the list once for each interval it is in. For example, the intervals (1, 4) and (3, 5) represent the list of numbers { 1, 2, 3, 3, 4, 4, 5 }.
The intervals will be given as two int[]s, lowerBound and upperBound. The i-th elements of these int[]s represent the smallest and largest numbers in the i-th interval, inclusive.
Definition
Class: UnionOfIntervals
Method: nthElement
Parameters: int[], int[], int
Returns: int
Method signature: int nthElement(int[] lowerBound, int[] upperBound, int n)
(be sure your method is public)
Notes
- n is 0-based, meaning that the first element is indexed 0.
- A sequence is sorted in non-descending order if and only if for each pair of indices i and j, where i is smaller than j, the element at position i is less than or equal to the element at position j.
Constraints
- lowerBound will contain between 1 and 50 elements, inclusive.
- upperBound will contain the same number of elements as lowerBound.
- Each element of lowerBound and upperBound will be between -2,000,000,000 and 2,000,000,000, inclusive.
- The i-th element of lowerBound will be less than or equal to the i-th element of upperBound.
- n will be a non-negative integer less than the total number of elements in the list, but no greater than 2,000,000,000.
Examples
0)
{ 1, 5 }
{ 3, 7 }
4
Returns: 6
The numbers are 1, 2, 3, 5, 6 and 7. The number at index 4 is 6.
1)
{ 1, 3 }
{ 4, 5 }
3
Returns: 3
2)
{ -1500000000 }
{ 1500000000 }
1500000091
Returns: 91
Watch out for overflow errors.
Problem Statement for SortEstimate (Binary Search)
You have implemented a sorting algorithm that requires exactly c*n*lg(n) nanoseconds to sort n integers. Here lg denotes the base-2 logarithm. Given time nanoseconds, return the largest double n such that c*n*lg(n) <= time.
Definition
Class: SortEstimate
Method: howMany
Parameters: int, int
Returns: double
Method signature: double howMany(int c, int time)
(be sure your method is public)
Notes
- lg(n) = ln(n)/ln(2) where ln denotes the natural log.
- Your return value must have a relative or absolute error less than 1e-9.
Constraints
- c will be between 1 and 100 inclusive.
- time will be between 1 and 2000000000 inclusive.
Examples
0)
1
8
Returns: 4.0
Given 8 nanoseconds we can sort 4 integers since
1*4*lg(4) = 4*2 = 8
1)
2
16
Returns: 4.0
Now that c = 2 we need twice as many nanoseconds to sort 4 integers.
2)
37
12392342
Returns: 23104.999312341137
We can almost sort 23105 integers, but not quite.
3)
1
2000000000
Returns: 7.637495090348122E7
Largest possible return.
Problem Statement for AutoLoan (Problem on Binary Search)
Auto dealerships frequently advertise tempting loan offers in order to make it easier for people to afford the "car of their dreams". A typical sales tactic is to show you various cars, and then talk in terms of what your monthly payment would be, to say nothing of how much you are actually paying for the car, how much interest you pay, or how long you have to make payments.
A typical auto loan is calculated using a fixed interest rate, and is set up so that you make the same monthly payment for a set period of time in order to fully pay off the balance. The balance of your loan starts out as the sticker price of the car. Each month, the monthly interest is added to your balance, and the amount of your payment is subtracted from your balance. (The payment is subtracted after the interest is added.) The monthly interest rate is 1/12 of the yearly interest rate. Thus, if your annual percentage rate is 12%, then 1% of the remaining balance would be charged as interest each month.
You have been checking out some of the cars at your local dealership, TopAuto. An excited salesman has just approached you, shouting about how you can have the car you are looking at for a payment of only monthlyPayment for only loanTerm months! You are to return a double indicating the annual percentage rate of the loan, assuming that the initial balance of the loan is price.
Definition
Class: AutoLoan
Method: interestRate
Parameters: double, double, int
Returns: double
Method signature: double interestRate(double price, double monthlyPayment, int loanTerm)
(be sure your method is public)
Notes
- Because of the way interest is compounded monthly, the actual interest accrued over the course of a year is not necessarily the same as (balance * yearly interest rate). In fact, it's usually more.
- In a real situation, information like this would typically need to be disclosed, but since you aren't at a point of signing any paperwork, the salesman has no legal obligation to tell you anything.
- The return value must be within 1e-9 absolute or relative error of the actual result.
Constraints
- price will be between 1 and 1000000, inclusive.
- monthlyPayment will be between 0 and price / 2, inclusive.
- loanTerm will be between 1 and 600, inclusive.
- The resulting interest rate will be between 0 and 100, inclusive.
Examples
0)
6800
100
68
Returns: 1.3322616182218813E-13
Noting that 68 payments of 100 equals the total price of 6800, so there is no interest.
1)
2000
510
4
Returns: 9.56205462458368
Here, we do pay a little interest. At 9.562% annual interest, that means each month we pay 0.7968% of the balance in interest. Our payment schedule looks like this:
Month | + Interest | - Payment | = Balance
------------------------------------------
| | | 2000.00
1 | 15.94 | 510.00 | 1505.94
2 | 12.00 | 510.00 | 1007.94
3 | 8.03 | 510.00 | 505.97
4 | 4.03 | 510.00 | 0.00
2)
15000
364
48
Returns: 7.687856394581649
This is similar to what purchasing a new car with no money down might look like, if you make payments for 4 years.
find out msb, (my solution was while (num >>= 1) { count++; } ) he then asked me to give a faster solution, which i did.
How would you implement the LRU cache mechanism
Explain the lifetime of an HTTP request. What happens if caching is enabled on your browser
write the insert function for the getting a balanced binary search tree given an array of integer to be inserted into it
Provide an implementation of the following interface:
public interface Powers extends Iterator<Long>
{
/* Returns the next integer a in the arithmetic sequence of integers where
* a = m^n, m > 1 n > 1, and m and n are both integers
* Thus, the first few outputs will be 4, 8, 9, 16, 25, 27, 32, 36, etc.
*/
public Long next();
/* Resets the sequence to the beginning, such that the next call to next()
* will return 4.
*/
public void reset();
}
what is 2 way cache?
Given a binary tree, write a program to find the cousin nodes of the given
node.
Write a program for a puzzle as following, there are eight pieces of puzzles contained in a panel which has nine slot,write a program to find out the quickest way to move the puzzle piece around in order to get all the puzzled ordered like the second
5 6
2 7 3
8 1 4
1 2
3 4 5
6 7 8
1) Explain all the fields in the IP header?
2) Explain the OSPF neighborship process?
3) He gave an example and he told me to explain Ip Fragmentation
4) Explain TCP initial sequence number
while downloading a file "hh" . how do u check that u have a duplicates of it in ur download folder ( 1 .a duplicate may present with different name 2. same name files and sizes can have different content are not duplicate ). strategies to find & optimize and make faster
Write The hash function for String as Key in hash table suppose u wants to retrieve the all the students in class using their name as key & their interest in subject as value so challenge here to write hash function for this class ..mind it key is String type & u can't use library function
Implement: read_lock()/read_unlock() and write_lock()/write_unlock()
Given: Mutex.lock & Mutex.unlock
What will be the three things you will look into when your java system.application goes slow suddenly. Means one day you notice application is running very slow and till yesterday it was fine, so what three things you will see first or debug first.
Given an array of n elements, how would you compute product of all (n-1) groups of elements? Take care of any corner cases too.
What different types of joins are there in SQL?
How will you do inheritance in C without using any C++ constructs?
Design a Data Structure with following operations
1.Insert(X) -> insert X if X not present
2.Delete(X) -> delete X if X present
3.Get() -> return any element if it is present
all operations in O(1).
No memory constraint.
You have a set of interdependent tasks (no loops), What data structures would you use and how would you find the correct sequence of execution of the tasks. For example: Suppose we have six tasks A,B,C,D,E. A depends on B and D. C depends on D. E depends on A, then one possible sequence is: B, D, A, C, E.
You have two lists, each containing position of a word in some document. Write a program that returns minimum distance between the words in the document.
For example: Suppose X occurs at places {2, 3, 5, 10, 12, 16, 19, 20} and Y occurs at {8, 14, 27, 29}, then the minimum distance between X and Y is 1 (X=12,Y=14 OR X=16,Y=14).
What is the size of a class which will have only one function declaration as public. And what is the size of a class if that the same function is declared as virtual.
class Myclass
{
public:
int fun();
};
Sizeof(Myclass) ??
And
class Myclass
{
public:
vitual int fun();
};
Sizeof(Myclass) ??Find the k-th Smallest Element in the Union of Two Sorted Arrays in (logn)..Please Write & Explain The Code Clearly
Given a binary search tree, design an algorithm which creates a linked list of all the nodes at each depth (eg, if you have a tree with depth D, you’ll have D linked lists).
Algorithm:
1) Put the root node in stack.
2) put all the node in queue(say queue1) till stack is empty
3) Create another queue (say queue2) from values of queue1
4) Generate the link list from the values of queue1
5) Iterate over queue2 and put all the left and right child of queue2 in stack.
6) loop over step 2 to 5 till stack is empty.
Topological sorting in graphs
pre-order traversal of binary tree
find an element in a partially rotated sorted array.
12 13 14 2 6 8
stack with min operation in O(1).
Given a stream of distance of millions of stars from the earth, find the nearest n star from the earth.
There are n buses in a city. Each of them carries at most m passengers. Find the probability that at least two of them carry the same number of passengers.
For a binary tree, print all possible paths from root to leaf nodes
Find median of an unsorted array (better in nlogn solution is needed)
A number is given as a palindrome, write a function to return the next largest palindrome.
A group of persons is fighting on a road. We have details about who punched whom, and there are only two groups, and a person will punch only a person from another group. What data structure would you choose for the input, output and write a fully functioning program for this.
A binary tree is represented in a array as the ancestor array, build the binary tree from this array.
eg
1
|
2---------------- --------------3
|
------------------
4 5
The array would be
1 2 3 4 5
1 x 1 1 1 1
2 0 x 0 1 1
3 0 0 x 0 0
4 0 0 0 x 0
5 0 0 0 0 x
where if i isAncestor of j, a[i][j] would be set to 1
Question 5 :-
* Difference b/w C++ & Java
* Multiple Inheritance in Java
* Difference b/w Overriding & Overloading
* Wrapper Classes
Question 4 : Asked basic concepts of OS like
what is an OS , functionality and necessity of OS ??
* Difference b/w Process & Thread
* Asked about Android , on what OS its based and then started asking Memory Scheduling mechanisms ,Disk Scheduling Mechanisms , Process Address Space , Process attributes
Question 3: Asked to print the path of the tree in zig-zag fashion
Question 2 : Explain the difference b/w C & C++ , C++ & Java
Write down all the features of C++ and explain each with an example
Yesterday i had interview @Motorola Mobility ..
The interviewer asked the following question
Questions 1 : Given a Linked List where a node points somewhere ( might be another node) but not the subsequent node. Find if such a link exists in the given list
Interviewer told that its called Malformed Linked List , since the link was pointing to random node instead behaving the usual way
* Reverse a Singly linked list given a single head pointer
Write the code for Dijkstra algorithm using adjacency list representation. What is the running time?
What will be the running time if adjacency matrix representation is used?
You are given an array A of k values which contain int values in sorted (asec) order. Find top k values (asec) which can either be the number from the array A, or sum of any two numbers from A or sum of any three numbers from A. So, if A's values are represented as : a1,a2,...,ak , the possible numbers can be: a(i), a(i)+a(j), a(i)+a(j)+a(l) for any i,j,l < k
Ex: A[7] = {3,4,5,15,19,20,25}
output B[7] = {3,4,5,(3+4),(3+5),(4+5),(3+4+5)}
There is a recursive function f(). It is looking at “cond” and then either returning or executing f() then g(). Consider “cond” to be an external variable that can be set somewhere else, perhaps in a different thread.
(1) If the first five times cond is checked, cond is == to true, but the sixth time, cond is == to false, describe the code flow.
(2) Because this is recursive, the code could suffer from a stack overflow if “cond” is == to true for too long. Fill in the function iterative_f() so that the code flow is identical to the code flow in (1).
//recursive
void f()
{
if(cond == false)
return;
f();
g();
}
//iterative
void iterative_f() {
}
data structures and methods for battleship game
program for atoi() conversion
a number is given as an array, 4567 is given as [4, 5, 6, 7] add 1 to this number and return.
In order traversal
traverse a binary tree. Did not specify any particular traversal. I just did it depth first.
IP address to decimal formula.
What happens to a program after you compile till its created to an executable.
Given an array of integers (positive or negative) find the lowest positive integer NOT present in that array.
Given an integer array of which both first half and second half are sorted. Write a function to merge the two parts to create one single sorted array in place [do not use any extra space].
e.g. If input array is [1,3,6,8,-5,-2,3,8] It should be converted to: [-5,-2,1,3,3,6,8,8]
Write test cases for backspace functionality for MS WORD. At each stroke of backspace how many bytes of data are deleted?
You are given a list of strings. Find a way to combine and store them in such a way that it you can retrieve the original strings
Answer: Add a Length <Marker> prefix before every string
Given a hash map of student IDs and scores to a function, return a map with student IDs and percentile marks.
Anyone is having algorithm for Multibyte backspace? If the previous character is single byte move one character. otherwise need to move 2 bytes.
There is a doubly linked list with next pointer and arbitrary pointer( points to an arbitrary node in list). You have to make a copy of the linked list and return. In the end original list shouldn't be modified. Best time O(n).
There are two linked lists and both are merging at a point. But the length of both the linked lists are different. How do you find the point of intersection of both these linked lists ?
How do we find the k-th element from the end of a linked list in O(n) time ?
Given a white background with a black random shape scattering around. Describe and code an algorithm to count the number of black shapes. You can assume input to be an array of 3xMxN in RGB color space.
You have given a dictionary and a string, you need to separate words that are in dictionary.
ex - catsanddog (here cat and cats both can be in dictionary)
output - cats and dog
You are given wooden cuboids with certain length, width and fixed height.
You have to place them one above the another with condition that whenever a cuboid is palced over another, its lenght and width should be within the lower cuboid. (less than or equal to).
Create an algo to achieve optimum height for given set of cuboids.
If you need to store one lack objects , which will be good HashMap or ArrayList ( don't bother about design issues like key/value pair)
Given a 2D matrix tell me how many path are there from (0,0) to (n,n) i cannot access the same cell once i visit it .
I have a array which has numbers from 1 to n one number is missing and one number is duplicated. find those in O(n)
If I have a string like
www.bing.com/abc/asd/asdffg/../asdasd/.../asda/../.../
this is a example ,
if you have /../ then dont remove the letters and / before , just remove /../
www.bing.com/abc/asd/asdffg/asdasd/.../asda/.../
Another example
if you have /.../ then remove the letters before and itself
www.bing.com/abc/asd/asdffg/../../
If the Fibonacci series is 1,2,3,5,8,13,….. then 10 can be written as 8 + 2 ==> 10010 and 17 can be written as 13 + 3 + 1 ==> 100101. Got it?? The Question was, given n, I need to get all possible representations of n in Fibonacci Binary Number System. as 10 = 8 + 2 ==> 10010 also 10 = 5 + 3 + 2 ==> 1110
Write a program to count the number of columns given the sample hitml like below:
<TABLE BORDER>
<CAPTION>A test table with merged cells</CAPTION>
<TR><TH ROWSPAN=2><TH COLSPAN=2>Average
<TH ROWSPAN=2>other<BR>category<TH>Misc
<TR><TH>height<TH>weight
<TR><TH ALIGN=LEFT>males<TD>1.9<TD>0.003
<TR><TH ALIGN=LEFT ROWSPAN=2>females<TD>1.7<TD>0.002
</TABLE>
On a dumb terminal, this would be rendered something like:
A test table with merged cells
/--------------------------------------------------\
| | Average | other | Misc |
| |-------------------| category |--------|
| | height | weight | | |
|-----------------------------------------|--------|
| males | 1.9 | 0.003 | | |
|-----------------------------------------|--------|
| females | 1.7 | 0.002 | | |
\--------------------------------------------------/
Had been called on-site at New York, there were 3 interviews - 1st one with 2 technical people, 2nd one with a team lead and 3rd one was HR.
I the 1st interview, first few questions related to my resume, thesis.
Then they asked me about network time protocol, inter-process communication, few other OS concepts, various run-time errors and examples when we get them.
Algorithm questions were:
1. Given a set of records of the form (ticket no, person name), ticket nos. are unique. find the person having the maximum number of tickets.
2. Write a function in C to calculate the average of a integer numbers stored in an array. They wanted to whether you consider all possible errors and code it without mistakes.
In the 2nd round the team manager asked some behavioral questions- team projects, how have you handled conflicts, etc. She asked me to design the music player for an ipod, which went on to different ways of indexing, searching.
Final round was a typical HR interview.
Given an array of integers A, give an algorithm to find the longest Arithmetic progression in it, i.e find a sequence i1 < i2 < … < ik, such that
A[i1], A[i2], …, A[ik] forms an arithmetic progression, and k is the largest possible.
The sequence S1, S2, …, Sk is called an arithmetic progression if
Sj+1 – Sj is a constant
Given a list of points in the plane, write a program that outputs each point along with the three other points that are closest to it. These three points ordered by distance.
An array is of size N with integers between 0 and 1024(repetitions allowed). Another array of integers is of size M with no constraints on the numbers. Find which elements of first array are present in the second array. (If you are using extra memory, think of minimizing that still, using bitwise operators)
Longest substring repeated multiple number of times.
Roman numerals to decimal
You have to paint N boards of length {B1, B2, B3… BN}. There are K painters available and you are also given how much time a painter takes to paint 1 unit of board. You have to get this job done as soon as possible under the constraints that any painter will only paint continuous sections of board, say board {2, 3, 4} or only board {1} or nothing but not board {2, 4, 5}.
You are given n segments. In turn, you take each one of them and join it with one among those already selected, creating either a loop or a longer segment. How many loops there are in average, at every instant of time?
In Binary tree .. from the in-order traversal and pre-order travrsal .. construct the tree
Consider two non-empty zero-indexed arrays A and B consisting of N integers each. Four functions are defined based on these arrays:
F(X,K) = A[K]*X + B[K]
U(X) = max { F(X,K) : 0 <= K < N }
D(X) = min { F(X,K) : 0 <= K < N }
S(X) = U(X) - D(X)
Write a function
double minfuds(int[] A, int[] B);
that given two arrays A and B returns the minimum value of S(X) where X can be any real number. Assume that the arrays have equal length and that it does not exceed 100,000. Assume that each element of the arrays is an integer in range [-1,000..1,000].
For example, given arrays A and B such that
A[0] = -1 B[0] = 3
A[1] = 1 B[1] = 0
A[2] = 0 B[2] = 2
the function should return 0.5 because
U(X) = -1*X + 3 if X <= 1
U(X) = 0*X + 2 if 1 < X <= 2
U(X) = 1*X + 0 if 2 < X
and
D(X) = 1*X + 0 if X <= 1.5
D(X) = -1*X + 3 if 1.5 < X
so for X = 1.5 function S(X) is equal to 0.5 and this is the minimum value of this function.
Design middle tier for facebook type application.
i.e design a service which accepts IIS requests from client and updates the database.
What are the various interfaces to be exposed on middle tier.
I was asked multiple questions around desgining a component and discuss about the APIs to be exposed. How do we approach such issues.
PS: They wanted me to talk about request context, notifications, callback, thread safe etc
How to check if a binary tree is AVL tree based on its depth rather than its height? Is the condition that maxDepth-MinDepth <=1 sufficient?
3.Given a binary tree,convert into a doubly linked list,The list must be as if the tree is traversed in zig-zag order from top to botton.. (left to right in one level and right to level in the next)
2.Given a doubly linked list with just 3 numbers 0,1,2 . Sort it
Amazon conducted a written test in hyderabad for SDE .Questions are.Although i wrote the solutions. I didnt clear the test. Not sure what they were looking for?.
They expected me to write a fully working code in any language.which i did.
Do they expect a specific solution which they already know?
or Do they expect the timing,space complexity to be at best
Anyway had a disappointing run
1.Given an infix expression convert into postfix
Design a social network - describe functionality to add a friend, delete a friend and check for mutual friends
Given one unsroted integer array, find out all the unique element in the array.
eg: Input: {23,53,1,3,6,23,1,7,9,53,9} Ouput;{3,6,7}
My solution:
Sort the array. Time: O(NlogN)
HashMap: Time: O(2N) Space: O(N)
Any improvement for this question?? Thanks.
Remove Duplicate slashes
"/root//foo/bar"=> "/root/foo/bar"
Obviously no extra memory and minimum number of elements moved
Design an alarm clock for a blind person.
What project are you most proud of doing, and why?
For SDE Interns...On-site Interview #4
Assume that you have 2^32 bytes of memory. When a program asks to allocate memory, a 4kb chunk of memory gets allocated. It can be allocated at any position (e.g. 0, 57, 8192). Now assume we have a function called lookup(), which, when fed an arbitrary address, (1) returns the value of the starting address of the chunk encompassing the requested address if it was allocated, or (2) returns a value indicating false if no block was allocated. Lookup must work IN CONSTANT TIME. To help clarify the functionality, here is some example expected behavior:
Allocate(1) /* allocates bytes 1-4096 */
Allocate(4099) /* allocates bytes 4099-8194 */
Lookup(123) /* returns 1 */
Lookup(4096) /* returns 1 */
Lookup(4098) /* returns -1 or false */
Lookup(6042) /* returns 4099 */
Lookup(8198) /* returns -1 or false */To the readers, my solution had 2 checks maximum (and thus was O(1)). I have provided the solution as pseudocode, java code, and given links to images depicting the reasoning behind my solution as responses below.
For SDE Interns...On-site Interview #3
Pretend you work for a phone company. At your company, you have a satellite that routes phone calls. We want to bill customers by the maximum number of simultaneous phone calls they make in a single day. (After asking clarifying questions I received the following information: assume no calls last more than 24 hours and that at midnight each night all the calls are automatically dropped. In the event that one call ends as soon as another starts, answer part 2 of this question in such a way as to maximize revenue).
What information should the satellite store for each phone call? Define a data structure for this (e.g. write a struct).
Write a function that finds the maximum number of simultaneous phone calls from a given customer. (Hint: typical solution is O(nlogn), but if you use an absurd amount of memory like I did, it can be done in O(n)).
Edit: Your solution should not be real-time. The data has already been collected and you need to work with it.
For SDE Interns...On-site Interview #2
In Microsoft Word, words that are misspelled are underlined in red. Which data structure would you use to identify misspelled words, and why? Be prepared to defend any design decisions that you make. Write a function that uses your data structure to check if a word has been spelled correctly.
For SDE Interns...On-site Interview #1
Please note I have posted all four of my on-site interview questions. I was completely grilled on my resume during all four interviews but didn't feel it necessary to add those questions.
Write a function to validate a BST. (I used a queue, so next he said) now, do it without a queue. What is the complexity of your solution?
Why do you want to work at Microsoft?
Why finance?
Why computer science?
What motivates you, what interests you?
Where are you interning? What would you do if they offered you a full time and we offered you a full time?
Why would you pick Bloomberg over the other company?
Where other are you interviewing?
Write a ‘translator’ program to convert a string (in C++ or other
language) into something which can be applied to the ‘where’ clause in sql
‘select’, here the string can be evaluated to a Boolean value, eg aa==3 &
& bb>12 || …
An array of size n+1 has integers only from 1 to n. The integers 1 to n can be present 0 or more times in the array. Find the first repeating element in the array.
Restrictions: O(n) algo required. Cannot use extra space(not even O(1)).
Write an algorithm that finds the contiguous subsequence of elements in an array with largest sum. The elements in the array can be negative.
Is there a O(n) solution for it? Any good solutions are very much appreciated.
Why Bloomberg?
const char *str;What does it mean? What can or cannot you do with it?
Bloomberg asks some very simple questions sometimes.
Given the following:
void foo (/* Add param here */) {
}
void main () {
char *str;
foo (/* Pass str somehow here */);
printf ("%s\n", str);
}Complete foo.
Follow up question was:
You probably used malloc or new in foo. That will cause memory leak. Write it in such a way so that memory does not leak (Basically use global or static).
Eazy peazy!
Given the stats that the highest occurring character in english text is 'e', given a cipher text as input, find out the plain text from it.
E.g.:
Given input "bloomberg", the highest occurring characters are 'b' and 'o'. Let's consider 'b'. According to our metric, highest occurring character should be mapped to 'e'.
So 'b' maps to 'e' in plain text.
Now shift all the other characters in the input to the output with the same shift offset.
Output for "bloomberg" = "eorrpehuj".
Also take care for character overflow, i.e. 'z' + 1 should map to 'a' (WRAP AROUND).
ALL CHARACTERS ARE LOWERCASE. Assume.
Given the input array:
[2, 3, 5, 6, 12, 4, 2]
The output array is:
[2, 6, 18, 24, 30, 35, 38, 40].
Find the pattern between the two and write a program to convert input to output.
Simple enough.
Given a MxN matrix, find the total number of possible paths from top-left to bottom-right element, you can go rightwards and downwards only.
Now, assume some of the entries in the matrix are blocked, find the number of such paths. For example: For a 3X3 matrix, total number of paths in first case is 6!/3!3! = 20.
For second case, if we block entry (2,2), we have only 2 paths available.
Given an unsorted array and two numbers, find the minimum distance between them. For example, if the array is {1,2, 10, 2, 3, 5, 2, 1, 5} distance between 2 and 5 is 1.
Given a sorted array of n integers, pick up k elements so that the minimal difference between consecutive elements is maximal (that is choose the elements to maximize the quantity min(a[i+1] - a[i]))
You have two BST, you have to merge them into a single BST, inplace and linear time.
Given x and y to a function, return x^y without using built in funcs.
Ans: Use recursion, solution in logarithmic time.
Write the code (either c++ or Java) to generate factorial of a number? Please don't laugh at it yet, the program must be highly scalable, it should (somehow) be able to return the factorial of a number as big as a million.
Give atleast 10 test cases for a program which finds and eliminates the duplicates in a singly linked list. assume it has all positive integers and returns the head of the linked list without the duplicates
Do anyone know about ION Trading, Noida ? How is the company/ job security /appraisals ? Thanks in advance..
How do you determine to strings are anagram. better than (nlogn) and should consider the wide characters also.
Suppose you have to implement the Google search bar that displays similar matches. How would you do it in constant time if there was no space limitation? Also, you are only displayed matches out of strings you have previous searched?
Eg. if you type "ba" you should display all your previous searches prefixed with "ba"
Round 1:
It was a kind of debugging round. The questions were:
1) Consider you are given a mobile alarm application how will u test
it
2) Consider ur gmail chat box is not working for a particular person
alone, wht will u do to find the problem
Consider there is an array with duplicates and u r given two
numbers as input and u have to return the minimum distance between the two
in the array with minimum complexity.
There is an array and the distance between any two consequent
elements is one(+1 or -1) and given a number. You have to check whether the
number is in array or not with minimum complexity
Suppose we are given an array A[1 .. n] with the special property that A[1] ≥ A[2] and
A[n − 1] ≤ A[n]. We say that an element A[x] is a local minimum if it is less than or equal
to both its neighbors, or more formally, if A[x − 1] ≥ A[x] and A[x] ≤ A[x + 1]. For example,
there are five local minima in the following array:
9 7 7 2 1 3 7 5 4 7 3 3 4 8 6 9
We can obviously find a local minimum in O(n) time by scanning through the array. Describe
and analyze an algorithm that finds a local minimum in O(log n) time.
print the 100th power of a single digit( which is of type int). How do you maintain that big number in memory?
print the 100th power of a single digit( which is of type int ). How do you maintain that big number in memory?
what is the difference between singele entry system &double entry syste
What is the data structure which suits best for the Battleship game? The board will be of size n x n, with m different ships each having k1, ..., km lengths. Each ship can either by place horizontally or vertically on the board.
The structures should be designed such that they can support basic operations for playing a game. For example, the board and a particular (i, j) coordinate representing a position on the board may be passed into a function attack(). The function should return hit if a ship was hit at that position, sunk if a ship has sunk after being attacked at that position, and miss if no ship is at that position.
Describe your design of the structures, what kind of data they store, and the runtime complexity of typical operations for playing the game (like the attack() function) as a result of your design decisions
You have a fair coin. Make it unfair with win and loose probability p and (1-p) respectively, where p is greater than 0 less than 1 tryv to optimize asmuch as possible write maths behind this clearly
Given an n-ary tree of resources arranged hierarchically. A process needs to lock a resource node in order to use it. But a node cannot be locked if any of its descendant or ancestor is locked. You are supposed to:
-> write the structure of node
-> write codes for
* Islock()- returns true if a given node is locked and false if it is not
* Lock()- locks the given node if possible and updates lock information
* Unlock()- unlocks the node and updates information.
Codes should be :
* Islock –O(1)
* Lock()- O(log n)
* unLock()- O(log n)
How to store costs for these considering combinations in most efficient manner:
* Source
* Destination
* Courier
* Weight etc
You need to optimize your search. Many question with different considerations
Write a class for finding next element in preorder traversal of a binary tree.
There is an integer array. The array represent a graph which increases till one point and then start decreasing. WAP to find the maximum number in that array. Write production quality code which handles all the scenarios. He also checked various combination of number with my code.
Think of the 8 vertices of a given cube. You are allowed to join three
vertices to form a triangle. How many such unique acute triangles can you
make ??
Discuss algo of insertion of an element in AVL tree, discuss complexity and code it.
This Time He wants from me clean & runnable code he walso told to write d program to rotate the tree
There is a doubly linked list with next pointer and arbitrary pointer( points to an arbitrary node in list). You have to make a copy of the linked list and return. In the end original list shouldn't be modified. Best time O(n).
we have to ttake careof next & prev pointer
What is index in RDBMS and what do you thing how they might be implemented? How will you implement?
Explain All Possible DS used for indexing & try to implement any one of them
i spend 1.5 hour on this..can any1 will suggest ??
Write code to check whether given tree is BST or not. ( initially I gave O(n^2) he said optimize then I gave O(n) and O(n) space then he said we don't have this much space then I was able to do in O(n) and O(1) space).
3. Whether code is thread safe?
4. How to make it thread safe?
i stuck in 2nd & 3rd part ..can any1 help...i dont wnats ans. of 1st part just explain me 2nd &b 3rd part
Design a system to manage clock room ( used at railway station). Like what data structure, how ? I gave O(1) time solution + small space complexity.
many irregular shape objects are moving in random direction. provide data structure and algo to detect collision. Remember that objects are in million.
In a unsorted binary tree, preorder, postorder an InOrder traversal has provided in the form of Array.
We need to verify all the three arrays are refering to the same binary tree.
I think we can do when it is sorted binary tree. Will convert of the array into Tree(eg., preorder) and compare this tree with another two traversal arrays.
Can someone help me understand the solution for this?
What happens behind the scene when we typ an url in browser and hit enter?
Given k sorted arrays each of length n, construct a single merged and sorted array.focus on running time and space complexity.
Source : Amazon interview question.
Any thoughts? thanks
.millions of book, how to find duplicates(book title may have error)
How to remove duplicate data from an array efficiently? Provide more solutions in the form with additional memory with O(n), O(n2) and nlog2n.
Questions based on Ad hoc networks and their behavior
Describe MIMO and how the streams are combined at the receiver side.
Describe LTE and EvDO phy layer
A frog has to cross a river. There are n rocks in the river, using which the frog can leap across the river. On its way across the river the frog can chose to skip a rock, but it cannot skip two consecutive rocks because that would be two far a distance for the frog to hop, also the from would not skip the first rock and the last rock. E.g. if there are 3 rocks, 1,2,3 and 4, there could be three following routes it could take:
1,2,3,4
1,2,3,4
1,3,4
1,2,4
Write a recursive algorithm, that takes a number of rocks' and prints all the feasible paths. Ofcourse there can be other arguments too.
There is a circle enclosed in a square,such that it is touching all the four sides of the square. In the top left space between square and the circle, there is a rectangle with length 14 and breadth 7, such that top left corner of the rect is the top-left corner of square and bottom right corner lies on the circumference of the circle. What is the radius of the circle?
There is a 2X4 matrix, in this you are supposed to arrange the numbers from 1-8, so that no consecutive numbers are adjacent(vertically, horizontally and diagonally) to each other. It is possible to do if one keeps on trying it randomly but it can be done with an intelligent approach too. What would that be?
Please send me the website of Magma company.
I see so many interview questions from Magma interviews. Are they hiring. Is it a good company and what do they work on.
Microsoft India development center Hyderabad had fired around 100 to 150 people. This news is not public.
If they fire people officially/publically, they have to give employee four month salary and hundred person bonus. And firing will create bad image in industry.
What they did is, they targeted set of employee and started documenting negative comment about those employee. Comment like: you should have design this; your code should not have any error, Your are lacking in xyz skill. They humiliated targeted employees so that employee resigns. If an employee resign, he or she can not file a case against Microsoft. They used this dirty technique to avoid legal issue in future.
Once they are done with documentation, HR asked targeted person to leave the company with “Termination letter” on same day since he/she hadn’t performed well. HR also gave option to targeted employee to resign and sit home for 45. Fear of having termination letter and losing job immediately, everyone took 2nd option to resign. This is bad.
This can not happen in USA. USA has very strong labor law and people respect each other.
Before you join Microsoft in India, think again. They are many good companies like google amazon oracle IBM etc.
How to find out the intersection of a link-list without using flags or modifying the link list
Rotation of a 32 bit number
DFS of a m-arry in non-recursive manner without using extra memory.
Recently i attended amazon interview. They asked me below question:
How much time it will take to fill up a floppy Disk?
there is a town which is a square grid.. every point can be reached from any other point.. there are 10 people in the grid.. find a common meeting ground for them such that the total distance travelled by those 10 people are the least..
Tell me all possible methods for removing duplicate elements from an array and sorted array....which one is the best according to you.
void main()
{
int i=0;
int array[5];
for(i=0;i<=5;i++)
array[i]=0;
printf("why this printf not working?");
}
Need to design a class for the following requirement.
Input => hello world(html)
output => hello%dworld
input=><>(xml)
output=><>
That mean if user pass any of the string , need to figure it encode string for each chracters and return the outut string.
These encoding character will change each application.
Once we complete encoding. Need to do decoding as well.
Can someone help to define the class and method for this?
We have two sorted array. Without using additional memory we need to merge these two arrays(second array is having more space for merging). Output should return through second array
I have gone through Mergesort from back to front and final data will be generated at the end of the second array.
This case second array or resultant array may have some empty spaces in the front. How to cleanup the empty spaces without using additional memory. That is additional question on the same algorithm
We have two unique sorted arrays. Need to find common elements from these arrays.
I have followed merge sort and get the common elements. Is there any efficient approch?
http://en.wikipedia.org/wiki/Proof_that_the_sum_of_the_reciprocals_of_the_primes_diverges
can anyone explain how it comes
\sum_{n=1}^\infty \frac{1}{n} = \prod_{p} \frac{1}{1-p^{-1}} =\prod_{p} \left( 1+\frac{1}{p}+\frac{1}{p^2}+\cdots \right).
plerase See harmonic..Serise..& explain how both are equals..
plz help
Count No of Set bits in Number in O(1)..yes its possible interview told me
Numbers are randomly generated and passed to a method. Write a program to find and maintain the median value as new values are generated.
Describe an algorithm to find the largest 1 million numbers in 1 billion numbers. Assume
that the computer memory can hold all one billion numbers.
Given a string with duplicate characters, find first unique
character (without using extra space)
Merge two unsorted array and remove the duplicate from the resultant array.
eg) Array1 = {"are","you","there"}
Array2={"how","are","you"}
output={"how","are","you","there"}
Can you guide me how to solve this problem efficiently.
What is the maximum size of the file that can be accessed in a virtual memory machine?
Can you access 5GB file in a 32bit system entirely at the same time?
How would you determine the max file size?
write a code to find the endianness of the system
8 ball problem. if given 8 balls with only one ball being a lighter weight and all other 7 being the same weight and given a scale, how will you find the light weight ball. do this in minimum number of steps
given a pointer to a single node of singly linked list, with no other details ( dont know where the head is) and its not a circular list, how would you remove only that node from the list
Large file is given ,which contains the english words.You will be given an utility which will return T9 encoding will be returned.Now you need to come up with an algorithm , that will group the words based on T9 encoding.
Ex : kate , gap ,late, apple .
O/p : kate ,late ,gap, apple .
Given array of integers , return an index such that it devides the array in 2 parts ,i.e.sum of all elements which are left side of the index = sum of all elements which are right side of the index. Do in linear time.
Given an unsorted array of numbers. Find if the array consists of consecutive numbers after sorting. Do this in linear time.
Example 1: If array has 5,2,3,1,4
after sorting we get 1,2,3,4,5 which represents consecutive numbers
Counter Example:
If the array has 34,23,52,12,3 after sorting we get 3,12,23,34,52 which are not consecutive
Write code for page fault handler in Linux ( I have a project on this so may be I was asked)
How would you turn a matrix (2D) by 180 degree...
1 2 3
4 5 6 would be turning by 90 degrees if we do it as
1 4
2 5
3 6
we have to turn it 180 degrees - another 90 degrees ( I did not understand this question properly)
Say there is an operation like a=b; Its the statement for which you want to avoid concurrency. (Say SMP or preemption or what ever)
With out using locks(spin,semaphore,mutex etc. etc.) how would you make this statement protected?
Ans: atomic operations (atomic assign etc.)
How would you debug kernel code.
How would you do benchmarking (compare the performance) in a device driver code? Apart from timing or time is there any other standard way? He basically meant comparing Programmed I/O and DMA. (Leave security etc. only performance comparison)
Say a function takes a pointer and allocates it some memory. How would the function 'Prototype' be?
Ans: void memallocate (size_ size, void ** p)
they wanted to know the double pointer declaration. He also asked why we give double pointer in functions that take Linked List head etc.
Count the no. of 1's in a 32 bit no. where there are mostly 0's in the number?
Since the no. has less 1's. Dont itereate on any mask or temp. instead, do this,
if (num > 0)
{
if(num >> 2 & 1)
count ++;
number = number >> 2;
}
this would make the number diminish each time and give a optimal solution.
How would you handle sleeping or blocking instructions in an Interrupt Service Routine(if unavoidable) or basically if the length of ISR is long?
Ans: Tasklets and Workqueues. PLEASE LET ME KNOW IF THERE ARE ANY OTHER.
Is sizeof() a macro or a function? I said macro... asked why not a function (leave alone the inline advantage of a macro)
Ans: In C there is no overloading. We send various 'Types' of parameters to sizeof. Macros dont do type checking. Hence Macros!
Do you have any experience with Multimedia or graphics or any codecs?
When would you use a hash table? Specific situations were asked
Write code for Strlen(char *). Write the test cases for this code.
You are given a pointer to a node of a min heap. The value of this node changes. Write a function that fixes the min heap.
Longest Common Prefix from N strings of max length "m".
I gave a naive approach of O(n.m) and O(m.logn) with some adjustments but Interviewer wanted something O(n+m) or better than O(n.m).
Please suggest solutions.
eg:
Flower
Flow
Flight
Output:
Fl
Given an array of n elements where next element will be + or - 1 of its preceding element given any random number you have to give its index(give any one index if the number has duplicate entry in array) in the array by using the property that next element is either + or -1 its preceding number.(Asked in second round of interview)
solution:-
given array as [4,5,6,5,6,7,8,9,10,9]
and suppose you have to find index of 9
Subtract the given number to be searched with the first element of the array
so here the difference is 5(|9 - 4|) check at 5th index in the array if number is not at that index again take the difference of the given number and the number at that index again search at now the difference is 2 (|9 - 7|) now check at 2 index after the (i.e 2 index after 5th index )which will be index 7 here number 9 index is 7 answer)keep on repeating until you get the number or run out of index.
How would you implement LRU cache algo.
1. "int get (key)" function should return the value of the key.
2.Set (key, value) function can set the value of an item if it present else it should add the item.
so the idea is when get or set function is called on an item it should become the most recently used items. While adding the item it should delete the least recently item.
Can you optimize the Get and Set functions of the algo so that it perform all the operations in constant time.
Assume an *infinite* array of integer which is sorted. How would you search an integer in this array. What would be time complexity.
Write a program to count the number of columns given the sample hitml like below:
<TABLE BORDER>
<CAPTION>A test table with merged cells</CAPTION>
<TR><TH ROWSPAN=2><TH COLSPAN=2>Average
<TH ROWSPAN=2>other<BR>category<TH>Misc
<TR><TH>height<TH>weight
<TR><TH ALIGN=LEFT>males<TD>1.9<TD>0.003
<TR><TH ALIGN=LEFT ROWSPAN=2>females<TD>1.7<TD>0.002
</TABLE>
On a dumb terminal, this would be rendered something like:
A test table with merged cells
/--------------------------------------------------\
| | Average | other | Misc |
| |-------------------| category |--------|
| | height | weight | | |
|-----------------------------------------|--------|
| males | 1.9 | 0.003 | | |
|-----------------------------------------|--------|
| females | 1.7 | 0.002 | | |
\--------------------------------------------------/
Given a Binary tree,find number of different vertical lines to intersect the all the nodes .
a
b c
ed
ans =3
We have a file or say book as input. Write a java code which can find the occurrence of every word on page.
We don’t want the number of occurrence; we want the number of pages on what word is coming. Take care of each and every word.
This question was asked in Nextag.
What do you do when you need a synchronize a collection.Using a synchronized collection is obviously not an option because of performance issues.
The other option is to use synchronized blocks when doing modification.
What would be an optimum solution for the above?
What are the key characteristics of an RTOS ? Compare those with that of a general purpose OS.
How does malloc work ?
What is virtual memory ? What is the pre-requisite in hardware for supporting virtual memory ?
how to find the longest ascending segment in an unsorted array using divide and conquer/
We have a tree and we need to set 200 values for each and every node. How to do it? Assume it is a binary tree and we need code in Java.
Unix Utilities - awk sed grep top du
Write an Efficient Program to build MinHeap...he wants from exact working code4..i tried..but not able to do it.can any one help me in this
Proove The Time Complexity of Sieve of Eratosthenes is O(nlog(logn))..Interview wants from clean Mathematical Proof..for this..
Best way to share a large file to 1000 computers in the same network.
design a algorithm for printing a book, since the pages in a book are binded, the page number changes if we add more pages. what is the data structure you can use best and why?
Explain how will you maintain concurrency in a key-value data store with replicas.
Consider a system containing processes. Each process has these details - pid, list of resources available to it and the list of resources that it will need to complete it processing.
Represent a system that would depict deadlock among these processes.
Given a large file with million lines of data(phone numbers), give a most efficient way to sort the phone numbers.
given an integer. Check whether its binary equivalent is a palindrome or not.
given a list of integers and a value K. Find all the pairs of numbers which sum up to K.
given a link list of integers delete all nodes which have value smaller than the value of any following nodes for example:-
7 4 5 2 3 6
answer will be 7 6
Design a data structure that supports integer of unlimited size.Assume that you have unlimited memory. Implement functions to support addition and subtraction.
you have a sequence where each number is a multiple of 2 or 5 (so: 2^i * 5^j). Given the beginning of the sequence as 1,2,4,5,8,10,16... and find a algorithm to calculate the next number in the sequence?
Convert Sorted Array to Balanced Binary Search Tree (BST)
i tried but it not giving correct o/p
for example u can take the array 12345 sorted...so can anybody help me in this
BinaryTree* sortedArrayToBST(int arr[], int start, int end) {
if (start > end) return NULL;
// same as (start+end)/2, avoids overflow.
int mid = start + (end - start) / 2;
BinaryTree *node = new BinaryTree(arr[mid]);
node->left = sortedArrayToBST(arr, start, mid-1);
node->right = sortedArrayToBST(arr, mid+1, end);
return node;
}
BinaryTree* sortedArrayToBST(int arr[], int n) {
return sortedArrayToBST(arr, 0, n-1);
}
How to define team hierarchy in one table? The main question was how we can define any hierarchy in single table, explain with team.
if(a>5) printf("greater");
else if(a<5) printf("lesser");
else if(a==5) printf("equal");
else printf("unknown");
in the following program what a value should be passed so that it print 'unknown'
Implement the tokenize function in C and how do you handle multiple spaces between words ?
So if the string is "abc def (2spaces)ghi" how do you separate out words in an array ??
Select a product and tell me what improvement you would make to the product.
System call? What happens in low level.
Signal handling mechanism.
Entry points into kernel?
struct {
char c;
int a;
char d;
}
What is the size here? What is the padding? Can we reorder these to reduce the padding? Why we need padding?
WHY (specifically WHY) do we have virtual functions (not just to access derived class methods using base class object. why we have to do that?
Ans: Library implementation or force interface approach by declaring a pure virtual function where user is forced to implement it, as is the case with interface.
Difference between Java and C++?
Implement anagram. Eg: eitx is anagram to xite.
ie - Same letters, order changed.
Did you see ICMP messages in TCP dump?
Have you ever analysed TCP dump?
How would you let other hosts know when there is a error? (I guess asked about ICMP header?)
What would happen when you press google.com?
Ans: ARP, DNS, etc.?
What would you do to test if another host is not responding? (Ping etc. etc. to test other host)
How many lines of C, C++, Java, Perl etc. code you have written in your life time?
Why NetApp
Implement strcpy function.
When would you use a hash table? Specific situations were asked
Write code for any pointer function.
Do you have any experience with graphics?
How do you debug?
Explain about what you cannot do in a ISR.
How would sleep in a kernel?
Difference between semaphore and mutex.
Write a pseudo code for page fault handler.
What is an ISR? What are the basic operations there?
Given a matrix (2D array). How would you rotate it 180 degrees? Clue: Swapping rows with columns rotates it by 90 degrees.
How do you improve performance of kernel code.
Various locking mechanisms
Delete the last node of a linked list? Also the data portion of a node in this list has a int *.
He meant free the data part also.
Why pass double pointers to functions? How would you declare the prototype of a function that takes double pointer?
Find the angle between min and hour hands of a clock.
Code to find the MSB
Macros vs Functions
What are Proxy servers
Describe the working of the internet.Procedure from writing the name of the URL to receiving the homepage on your screen
Asked if I knew Poker. I said no, so then asked me to design deck of cards, Just the class and methods.He did not want the implementation of any method, just signatures and return types.
Given an array of integers all but 1 appear even number of times, Find the integer that appears odd number of times.I gave the XOR solution. Then he said what if its an array of objects and not integers. I said I would use hashtable.He asked me to write the code for that.
There was some glitch in my code in the return value. So he asked how I would handle that in Java. I told using try-catch. He said OK and then asked when do you use Exceptions in java?
what are final, finalize and finalizer in java?
when do you use "equals" in java?
when is "equals" overridden in java?
why cant you just use "==" instead of "equals"
describe the concept of polymorphism
Given a binary tree of depth d, print all the paths from root to leaf.
what are final, finalize and finalizer?
what are final, finalize and finalizer?
Write a Program to remove loop from linked list..program should be clean & should pass all test cases..he wants from me exact working code
You are given a function printMostFrequentWords which takes in an array of strings. You are required to print a list of all the letters that occurred with the highest frequency in each line of the file, followed by the frequency.
The list of letters should be an alphabetical list of upper case letters followed by an alphabetical list of lower case letters.
Sample Test Cases:
Input #00:
When riding your bicycle backwards down a one-way street, if the
wheel falls of a canoe, how many ball bearings does it take to fill
up a water buffalo?
Hello Howard.
Output #00:
e 6
al 7
a 3
Hlo 2
There is binary tree with special property that all its inner node have val = 'N' and all leaves have val = 'L'. Given its preorder. construct the tree and return the root node
Given a link list. Determine if it is a palindrome.
I know that String is declared as a final class in Java, so we can't extend the class. Than how we are able to use methods from String class like toString(), equals() etc, because they are non final methods.
There is an array in an external system (i.e. u cannot access the array elements directly). The system exposes 3 functions of O(1) :
length() - returns the length of the array.
get(i) - returns the element at index i.
reverse(i,j) - reverses the elements in the array from index i to index j (both indexes inclusive).
Can you sort the array in the best possible way using only these 3 operations?
WHAT IS THE OUTPUT OF FOLLOW C PROGRAM?
#include<stdio.h>
#define TOTAL_ELEMENTS (sizeof(array) / sizeof(array[0]))
int array[] = {23,34,12,17,204,99,16};
int main()
{
int d;
for(d=-1;d <= (TOTAL_ELEMENTS-2);d++)
printf("%d\n",array[d+1]);
return 0;
}
There is an array of positive integers...all the elements in an array is repeated even number of times except one number,which is repeated odd number of time...WAP to get that element which is repeated odd number of time...After then he asked me to test the code...
Generate nested () based on the input given.
ie. if n = 3
O/p
((()))
()()()
(())()
()(())
(()())My solution is as follows
#include <iostream>
#include <vector>
#include <string>
using namespace std;
void printPar(int l,int r,string s)
{
if(l > 3 || r > 3 || r >l)
return;
if(l==3 && r==3)
{
cout<<s<<endl;
return;
}
else
{
if((l<3))
{
s+="<";
l = l+1;
printPar(l,r,s);
}
if(r<3 && r < l)
{
s+=">";
r = r+1;
printPar(l,r,s);
}
// cout<<"Exiting "<<l<<" & "<<r<<" "<<s<<endl;
}
}
int main()
{
string s;
printPar(0,0,s);
return 0;
}
Output :
<<<>>>
<<<>>>
<<><>>
<<><>>
<><<>>
<><<>>
<><><>
<><><>This one is straight out of the book , the code given in book is wrong. Can any one help in correcting my logic.
understand why there are duplicate values in the list. i.e once the function is called using recursion and ends up following the next branch on execution. The second print is due to the function it self falling on the second branch. Is there any way to handle this ? I really do not want to go the global-set route.
Also , in my head this code should print (())() - Yet it does not :(
Can some one please point out the error ?
Given a binary search tree and a target number n, write a code that can find the largest number inside the binary tree that is smaller than the target number n.
You are given an array that contains integers. The integers content is such that every integer occurs 3 times in that array leaving one integer that appears only once.
Fastest way to find that single integer
-- using memory.
-- not using any external memory.
eg: [2,1,4,5,1,4,2,2,4,1]
Given a finite number, find out all the possible strings that can be generated by using encoding found on phones for eg 112 => bad,bac,aae...etc. ( since 1 = abc , 2 = def ... )
Given the current time as input( e.g 1,40) , find the angle between the hour hand and the minute hand.
Initially you have a 2x2 matrix, say zoom1:
a b
c d
zooming it results in a 4x4 matrix (zoom2) as follows:
aa ab ba bb
ad ac bd bc
da db ca cb
dd dc cd cc
zooming it again will result in an 8x8 matrix and so on..
The question is, given a sequence say abaaccda... we need to find out the sequence coming just left to it. For e.g. if the given sequence is "bd", the sequence coming just left to it is "ac". For "cb" it's "ca" etc. [Amazon Hyderabad]
Given two sorted arrays of integers, write a function to determine the median(s) of merged array. Note: no extra space to be used. Discuss the complexity also.
Given a singly link list, you have to keep first M nodes and then delete next N nodes, again keep M nodes and delete next N nodes and so on. Write all test cases also. Discuss the time complexity also.
Implement strcat in C.
There is a string suppose " &%..123..& 345 ".
Make a linked list from this string having elements as 1->2->3->4->5.
Design the game BOGGLE.
Implement listIterator.
Find the depth of a tree.
Implement (get and put) functions of hash table.
All the elements in the array are even in number except one. Find that element.
Implement atoi function
(Round 3)
Given a binary tree, find the largest subtree which is a Binary Search Tree (BST), where largest means subtree with largest number of nodes in it.
____10____
/ \
__5_ 15_
/ \ \
1 8 7
____10____
/ \
__5_ 15 -------- subtree (1)
/ \
1 8
__5_
/ \ -------- subtree (2)
1 8
1st is maximum so we need to find that BST ..
he again told me write the exact working code,.so only coding can save you...else nothing..try to write efficient code
(Round 1)
Write A Program to Remove Duplicates from BST remember its BST not Binary Tree...He Asked me to write neat & Clean Code fro this so try to code your best
write-a-program-to-add-two-long-positive-numbers-each-represented-by-linked-lists/
also do it with out reversing linked list
Explain Efficiently
You are given a matrix M[n, n] for a tree with n nodes. In the given matrix M, M[i, j] is true if node j is an ancestor of node i. Construct the tree from the given matrix.
For example, you are given below matrix.
1 2 3 4
1 0 1 1 0
2 0 0 1 0
3 0 0 0 0
4 0 1 1 0
You need to construct the below tree. In the constructed tree ancestor relationship should be correct. A node can come on left or right of its parent as you cannot determine this information from the ancestor matrix
Node numbers used in matrix are in bracket
5(3)
|
|
10(2)
/ \
/ \
12(1) 13(4)
Given a Special BT in which Each Non Leaf Node Except Root Has at-
least two children .Given Pre-order and Post-order of Tree Your Task
is to design the tree From the Given Information..
Thanks & Regards
Algoseekar
If two strings s1 and s2 are given find out they are anagrams are not
"abc" and "bca' are string anagrams
characters will be same in both but order may change
W.A.P to construct tree from inorder and preorder are given
And also askerd can we construct B.S.T from only post order or preorder string given?
W.A.P For Printing pascal triangle:
Which is defined as
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
design a boolean functions to check whether two strings are anagram or not in O(n)
Design a class to serialize / deserialze a graph.
Design a class to process a matrix, and it needs to be able to return the average for the elements of arbitrary sub-rectangle inside that matrix, in constant time.
rOUND 5:
Achievements, weaknesses, strong points, etc...
Round 5:
A tournament occurs in which, each players plays every other player.
Arrange the players such that the player have defeated its immediate left player in the match played between them.
Best case : O(n) Worst Case: O(n2)
Round 5:
Monte Carlo Probability problem. 3 gates and treasure behind ....
Round 4:
Design Lift using OOPS concepts.
Round 4:
Questions on paging and segmentation. How virtual address is translated to physical address.
Round 4:
Garbage collection algos, questions on process and threads.
Round 3:
Implement Big Integer addition in C.
Round 3:
An array contains all but one number even number of times. Find that number.
Round 2:
Implement shuffle api
Round 2:
Generate nth anagram natural number.
like 1,2,..,9,11,22,..,99,101,....
Round 2:
One more question of graph. Standard UVA question.dont remember exactly.
Round 2:
Find the number of digits in n!.
Round 2:
Generate valid pairs of paranthesis for a given input n.
()(),(()),..
Give DP solution.
Write Context Free grammar for it.
Round 1:
Design stack with give lowest element(by value) operation in O(1) time.
Round 1:
Array a contains integers.
Form new array b such that
b[i]= product of all elements in a except i the element.
You cannot use division.
Give solution of O(n) time.
Round 1:
Find Lowest common ancestor in a btree
Create a doubly linked list from a binary tree such that an ith node in list contains the sum of the elements on ith vertical line of the tree
Merge two sorted linked list
Sorted array rotated by offset k. Find element in it.
There are two poles of equal height 15mts. One cable with length 16mts is hanging between that two poles. The height from center of the cable to earth is 7mts then what is the distance between that two poles.
How to solve this ?
Develop the conversion function among UTF-8, UTF-16 and UTF-32 in C, and test it.
In the CrackingTheCodeInterview book solution, CareerCupLibrary - TreeNode, the isBST method is like this:
public boolean isBST() {
if (left != null) {
if (data < left.data || !left.isBST()) {
return false;
}
}
if (right != null) {
if (data >= right.data || !right.isBST()) {
return false;
}
}
return true;
}But I think this method only checks whether the tree is searchable, it can NOT check whether the tree is balanced. Am I right folks?
Implement "strstr" function in C. What is the time complexity of your algorithm
Write a c++ program to find the LCM of all the elements of an array.
Find kth largest integer from an unsorted array of integers. Provide O(n) algorithm.
Initially there is a array of integers sorted in ascending order. Later, first few elements of the array are left shifted so they wrap around and become the last elements of the array. The order within those shifted elements is preserved. Write algorithm to find given element from the array in O(logn) time.
e.g. Say initially array is 1 5 10 15 20, after left shifting by 2, it becomes 10 15 20 1 5. Search element in this array.
Write code for the same.
What is the difference between sendRiderct and forward?
everyone knows the difference but now the main question is what happens to parameter which were sent in request and than either redirect or forward. Does the parameter remain in request or do we need to send again?
Implement a function to detect memoryleak
You are given N ranges of date offsets when N employees are present in an organization. Something like
1-4 (i.e. employee will come on 1st, 2nd, 3rd and 4th day )
2-6
8-9
..
1-14
You have to organize an event on minimum number of days such that each employee can attend the event at least twice. Write an algorithm (there is apparently an O(n) algorithm for this).
(2nd phone screen)
write a function isBST() that should tell if a binary tree is BST or not
(2nd phone screen)
reverse pair of elements in a linked list.
eg. abcdef shouldbecome badcfe
most memory-efficient way to store 1 million phone numbers?
i'm debating between two structures and wondering what everyone else thinks.
You are given a Binary Search Tree.Convert it into a circular doubly linked list without creating extra node.covert just by changing the pointers of the BST nodes.
Describe in brief the data structure you will use to implement the game of snake(mobile game).
Describe in brief the data structure you will use to implement the game of minesweeper.
Describe in brief the data structure you will use to implement the game of snakes and ladders.
Using recursion return the number of leaf nodes and non leaf nodes from a single method without any global variables for a given BST?
You are given a function. When it is called, it returns 0 with 60% probability, and 1 with 40% probability. Now using this function, write a new function that returns 0 with 50% probability and 1 with 50% probability.
An array of integers contains negative numbers and positive numbers, then arrange the array in that way sothat -ve number and +ve number in alternative place. remaining extra -ve number or +ve number put at last.
e.g.
-1 -2 4 5 6 -3 9 -8 7
output: -1 4 -2 5 -3 6 -8 9 7
TO write the String Tokeniser function for strseps.lib using pointers in C
how to crash your system immediately?
Preparing sets from a given array with min complexity.
S1=1,2,3,4,5
stes = {1},{2},{3},{4}..{1,2},{1,3}..{1,2,3,4,5}
Implement Queue using Stack. Help to get a code with resolving complexity.
Write a new function Malloc(size, alignment) which uses the old malloc but also returns an aligned address!!!
What is Memory Alignment?
Can Two Processes have the same Virtual Address?
Difference between a MUTEX and a SEMAPHORE?
Does Malloc give a memory aligned address?
What is MMU made up of? (with reference to data structures)
Program to reverse the linked list!
Write a C program to interchange the nodes of a linked list. Consider the linked list 1->2->3->4->5. You should get the o/p as 2->1->4->3->5. The pointers should be exchanged not just the data!
Implement a MACRO(i,j,k) where i is a Hex number, j is the bit position and k is 0/1. So based on k, jth bit in i should be replaced. (Not no IF stmts allowed nor For loops in a macro)
We have an array of bytes, every elements of array contains '0010011' type of representation. Write a java program which can find how many 1's are there in array.
If we add a signed integer and a unsigned integer, will the result be signed or unsigned? What I guessed was signed, but after searching online for a while, looks like I was wrong. Can anybody give more detailed explanation?
You have n infinitely large sorted streams, and you have to get an output stream which returns the combined stream..
end of the battle!
difference between array and pointer
how can u find the size of structure.
How can four employees calculate the average of their salaries without knowing other's salary?
Given N students, find the number of ways the students could be ranked. Also one or more students can have ties and can have the same ranks. I was stumped at this question. Seem like a dp question?? Any suggestions?
-Binary Tree - BFS without recursion.
I used queue for this.
- Flood fill algorithm
How to print this:
1
11
21
1211
111212
31121112
this means you have to count like. In first line there is ' one 1 that's why second line is '11', now in second line is 'two 1', so third line is '21'. We have to count the appearance and print the number of appearance and number.
I heard some people mentioning an onsite test for developer position. I was wondering if any of you had to take it. Also, what kind of questions were on it? Thanks!
I was asked basic loop detection in a linked list problem. I answered it. But the follow up question made me stuttered.
" How do you find the beginning or starting point of the loop in the linked list ". Anyone have any idea?
Given a string (assume there no spaces or punctuations), write a code that returns the max. length of the string that has repeated more than once.
What are stacks and queues? Give an example for each.
Give a set of phone numbers. Check if there are any duplicates. only algorithm.
There is one pdf file with lots of Unix commands and text. Write a java program to read that file and execute those commands on DOS (Windows) and output should be displayed on console also And copy that file on some other place also as it is.
There is a Furniture class and has derived classes like WoodChair,WoodTable,SteelChair,SteelTable. She wants to add more number of classes like ironchair,irontable etc; How would you do that. The design is not yet published and you are free to modify the entire sutff given.
implement atoi function.
There is a website and clients visit it multiple times. Also a log file which keep track of client id, visited url, date visited. Print the client id, url, no of times it is visited on a particular day.
Explain about a project that you have worked on and the one u like most?
Write a program to reverse pointers of a binary tree?
Means to reverse all the pointers like at the beginning root points to children..The function should reverse pointers such that children point to root...
I hope I am clear...
Write a function
int triangle(int A[], int n);
which given a zero-indexed array A of n integers returns 1 if there exists triple i,j,k ($i\not=j\not=k$, $0\le i,j,k <n$) such that:
A[i] + A[j] > A[k]
A[i] + A[k] > A[j]
A[j] + A[k] > A[i]
or returns 0 otherwise.
Examples:
For:
A[0]=10, A[1]=2, A[2]=5, A[3]=1, A[4]=8, A[5]=20
your function should return 1, since for i=0,j=2,k=4 all conditions are fullfiled (i.e. A[2]+A[4]>A[0]).
For:
A[0]=10, A[1]=50, A[2]=5, A[3]=1
your function should return 0.
Design a class for a bakery.
Given a cycle of n nodes. Each node has a money Bi and each edge of the cycle has a cost Ci.Now when i am at a node, i acquire the money at the node and if i have to move to the next node in the cycle , i have to pay a cost corresponding to that edge. Now the cycle is unidirectional and we define a trip as starting from a node and coming back to it. Answer the following questions:
1. Give a necessary and sufficient condition for a trip to exist.
2. Given 1, give an algorithm to find the start node.
How do you sort a linked list? What type of sort you will select and why?
what data structure does the std::set use? How would you insert items to a red-black tree?
questions about hashtable. what affects lookup speed?
How does a compilier work?
convert a binary tree to binary search tree inplace. We cant use any extra space.
You are given n petrol stations s(0), s(1), s(2), ..., s(n-1) which have petrol available p(0), p(1), p(2), ..., p(n-1). Going in a circle, with distance to next station being d(0), d(1), d(2), ..., d(n-1), how will you find where to start, such that you can complete the loop. You can assume mileage to be 1.
Implement enqueue and dequeue operations using stack(s).
What subtleties you will look for while writing an atoi program? How will you detect overflow? Write a program to add two numbers represented in string and return the sum as string.
How will you detect if two rectangles intersect and find their intersection. Write test cases for same.
Print a 2D array spirally.
Write test cases for copy command in UNIX.
Given a sorted array and a number, find two numbers which sum to the number. Write test cases for same.
Given a BST, print all nodes lying between two values, inclusive of these values. Write test cases for same.
Given a tree where each node points to its parent, find LCA of two nodes. Write test cases for same.
There are two string array with some uniqueue srings. Need to find out first arry uniqueue values in the 2nd array.
S1={"Albert","Matt","Jackson","Steve","Ven"}
S2={"Kelos","Dragi","Matt","Ven","Possi"}
Answer={"Matt","Ven"}
Please provide us O(n) solution to the above.
Count the number of binary 1's in an integer.
My Ans:
//assume 32 bit number
int num = given number;
int count =0;
if (num%2 != 0) count++;
for (int i=0;i<32;i++)
{ if((num = num>>1)%2 !=0)
count++;
}
print count;Design a data structure for storing Movies and their ratings given by users. Ex: similar to netflix or Imdb
Write a function "int overlap(Rectangle *a,Rectangle *b)" that returns 1 if the two rectangles overlap, 0 if they don't.
typedef struct
{
int x,y,width,height
} Rectangle;
Write a function "int add1(int val)" that returns val+1 without using +'s or -'s anywhere in your code. Yes, you will probably need to do some bitwise operations to accomplish this.
Write a function to reverse a string without allocating a temporary buffer
Reverse a linked list using recursion
Write an algorithm and explain the data structure used in the travelling sites like makemytrip.com ,cleartrip.com to give the results.. its a graph problem...
How to find a number of 10 digits (non repeated digits) which is a perfect square? perfect square examples: 9 (3x3) 16 (4x4) 25(5x) etc. Ten digit number example 1,234,567,890
output of following Program
class A
{
public:
virtual void Fun1(int no=10)
{
cout<<"A::Fun1";
}
};
class B
{
public:
virtual void Fun1(int no=20)
{
cout<<"B::Fun1()";
}
}
int main()
{
B b;
A &a =b;
a.Fun1();
}
3. Given a number of nodes N of a binary tree , how many structurally different full binary trees are possible.
A binary tree is said to be full binary tree , if for every node in the tree there exists exactly zero or 2 children.
Example: When N = 5 , No. of possible trees = 2
o o
/ \ / \
o o o o
/ \ / \
o o o o2. Given a binary tree , write a function to determine whether its a balanced binary tree.
A tree is said to be balanced if for every node, difference in height of the sub trees are not more than 1.
bool isBalancedBinaryTree( BinaryTree * root);
This question was asked in Amazon recruiting Event for SDE chennai position. The event happened in Hyderabad , India.
1. Given a linked list with a set of elements , group the elements into even and odd numbers.
Example. Input: 1->4->6->7->10->13
Output: 1->7->13-> or 4->6->10->1->7->13
The output can be any one of the above. Either you can have odd numbers followed by even or vice-versa.
Write code to create a form with two tabs. First tabs contains a form which has name, address etc. After filling first form when we click submit button, page goes to second tab which has some information or something. You have to write in javascript/css/html.
Both tabs should be visible, but not forms.
Design a Thread safe Array Based queue with a fixed size.
The behavior should be in such a way that if multiple threads are accessing the same queue and if the queue is full the threads will wait for their turn and if some other threads removes elements from queue, the waiting threads will get a chance to add elements.
you have 2-d array, with m length and n width.You are also given k,
( k<=n && k<=m ).
Now, select a square of size k, which returns maximum sum.In Minimum Time Complexity
Create a Singleton class which has only one static method? static variable or new is not allowed
function to generate random number without using any built in function.
convert string into integer without using any built in functions.
What is result for:
float f1 = 0.0f, f2;
do
{
f2 = f1;
f1 = f1 + 1;
}
while (f2 != f1);
I had interview at Google.It was goog experince
If there is dictionary of words and you want to add new word into that dictionary and u have to find whether that new word is combination of two words which are already in dictionary
e.g you want to add newspaper then there are words news and paper in dictionary you have find it with minimum compexity. I answered trie structure but stucked with complexity then hash but he didn't satisfied
What is wrong with this piece of code.
int main()
{
for(;;)
{
short n;
scanf("%d",&n);
if( n == 42)
break;
}
system("pause");
return 0;
}I gave 3 phone interviews with linkedin. HR gave me 2 options
1. I can come on their batch recruitment day for new grads and I will supposedly meet 4-5 teams on batch day
2. I can pick a team, attend a skype video interview with shared coding and come separately on a non-batch day if I clear the skype screen.
I am very confused as to which one to pick. Has anyone undergone this process before?
Given an integer array, sort the integer array such that the concatenated integer of the result array is max. e.g. [4, 94, 9, 14, 1] will be sorted to [9,94,4,14,1] where the result integer is 9944141
Card shuffle problem. I have a card pack of 313 cards. I remove the topmost card from card pack and place it on desk and I remove the next one and put it below the pack of cards(that you are holding). keep doing this till all the cards are on desk. Pick up the card stack from desk and repeat these steps till you find retrieve the original cards orderd. I was asked to code to find how many rounds it will take to retrieve initial order.
How we can achieve internalization on UI level say JavaScript?
Why do we need hashcode() method, when we have equals()?
A typical email message contains message headers followed by a blank line followed by the message body. Received headers begin with "Received:" and detail the mail systems that the email was routed through.
3. Please extract the IP addresses from the received headers of the messages.
Please extract domains from the body of the messages.
Note:
- The body of the message is separated from the headers by a blank line.
- Domains appear as part of URLs. For instance, a url looks like:
http://www.domain.com/xyz.html
The domain would be domain.com.
4. Please use PHP, Perl, Python, C, or C++ to complete this exercise. If you decide to use C or C++, please also submit the make file or project file to compile on Linux or Windows.
Assume you have a set of 1500 independent pieces of code. We'll call them projects. Each project can either be:
1) completely independent
2) dependent on other projects
3) dependent on other projects and have other projects dependent on it
The combined build times of all 1500 projects is 24 hours(so build project 1, when it finished, build project 2, etc). A build consists of compiling and linking all the requisite code. You can assume you don't have to worry about a budget. If there's a tool that would help you out, you can use it if you can describe how it works. How would you speed up the build process?
Describe your projects
<round 2>
16. Find out largest common SEQUENCE
e.g:
1)
str1: ABCDEF
str2: ABC
LArgest Common sequence: ABC
2) str1: ABCDEF
str2: ACEG
LArgest Common sequence: ACE
3)
str1: ABCDEF
str2: ZACYEFX
Largest common sequence : ACEF
NOTE: SEQUENCE need not be consecutive .
<round 2>
15. We have a special tree, in which every node contains random number of child nodes.
Note : each node can contains no. of child nodes between ZERO to INFINITY
sub questions:
1) node structure definition ?
2) which traversal you use ?. Traversal code ?
<round 2>
14) How you will achieve encapsulation in C language ?.
<round 2>>
13. Different types of TYPECASTS in C++ ?
<round 2>
12. Iterative Binary Search Algorithm with Single comparison .
<round 2>
11. Explain PREORDER, POST OREDER, INORDER. ?. To construct tree which 2 ORDERS needed ?
<round 2>
10. How many ZERO s in 100! ?
<round 2>
9. How to check given number is prime or not ?
<round 2>
8. Number N is given to you. You have to print all Permutations between 1 to N.
e.g
1) N = 2
o/p: 1 2
2 1
2) N =1
O/p : 1
<round 2>
7. Quick Sort avg and Worst case complexity . write code for Quick sort ?
<round 1 >
6) what is fork()
sub questions
1) How many times "SIVA" will be printed
i = 0 ;
while (i < n )
{
fork();
printf("\n SIVA");
i++;
}2)How many times "SIVA" will be printed
i = 0 ;
while (i < n )
{
printf("\n SIVA");
fork();
i++;
}<round 1>
5) Explain about Thread Pool ?
<round 1>
4) Difference between Flip-FLOP ? Where we use flip flop ?
<round 1>
3) Unbalanced or Skewed binary tree root is given to you. You have balance tree by doing LEFT and RIGHT rotations.
<round 2 >
2) Write your own "cp" command to copy files.
<Round 1>
1) Iterative Single Linked List Reverse
Write code to find the longest palindrome in a string.
You are developing a system for a cell phone which will automatically predict what word a user is typing. Talk about the data structures and algorithms you would use to make this, keeping in mind that cell phones have limited memory/CPU power.
Design the ER diagram for a movie rental store.
Given a BST in a language where memory must be handled manually, how do you completely remove BST from memory? Recursion is not allowed. Was later told that desired solution had O(N) time and O(1) space.
Given two strings, write a function that returns true if the second string contains all the letters from the first string.
When is a finally block executed? Give an example of when to use one.
There are 60 sailors in my galleon,plus half the crew again,how many sailors do we have?
You have 20 barrels of rum,divide by a third and add 10,how many do you have?
There are N web servers. Each web server has a huge file containing random 1 million numbers (numbers can repeat). Find the median of these N million numbers given that only 1 million numbers can be brought into memory at a time.
Code for a method that takes two arrays and returns true if one array is contained in the other..
1,2,3,4,5
2,3
true
1,2,3,4,5
2,4
false.
Experience working at CISCO INDIA. refer to the third reply for the actual post
A complete ternary tree is a tree in which each and every node has either 0 or 3 children . Given preorder of a complete ternary tree , construct the tree . Preorder will be a string containing characterd i and l where i represents an internal node and l represent a leaf node .
Find the number of strings of length n having u distinct uppercase letters , l distinct lowercase letters and d distinct digits
Given an array and an integer k , find the maximum for each and every contiguous sub array of size k.
Sample Input :
1 2 3 1 4 5 2 3 6
3 [ value of k ]
Sample Output :
3
3
4
5
5
5
6
Given an integer n , you have to print all the ways in which n can be represented as sum of positive integers
Count the no of words in a string. there could be arbitrary no of punctuation marks. do not use functions like split.
Check if two given strings are anagrams?
A 100-sided die, you get a second chance. Your strategy and expected payoff...
What difference in behavior you find between Virtual destructors and other virtual functions and why?
Hy there are 4 questions asked in microsoft written paper in bangalore-
1) you are given a function prototype like
char * replace(char *str,char *find,char *replace)
you need to code it and specifications are-
str is input string .
find is a given pattern and you need to find this pattern and if it exist replace it with another string (replace).
for example-
if you are given input string "aabcdef" and find pattern is "bcd" and replace string is "xyz" then output string should be "aaxyzef".
Also if Input string is "aabcdef" and find pattern is "bcd" and replace string is "xxxx" the output should be "aaxxxxef".
2) Write top 10 Scenarios for above code and three most critical test cases for above code.
3) Write top test cases to test coffee vending machine.
4)There are 8 cricket teams say t1,t2,t3,..t8 and each team plays two matches against each team one match in india and one match in abroad.these matches are known as league matches. Now after league matches top 4 teams(top scorer) will enter semi finals.Some data is-
A) each win gives one point to winning team.
B) There is no draw in any match.
C) at any point if scores of any two teams are equal then winner is decided by an automatic machine and is out of your control.
Now find-
x) Minimum number of matches to win so that a team can qualify for Semi finals.
y) Maximum Number of matches won by a team when it canNOT qualify for semifinals.
Given a sudoku puzzle that is not completed yet, how to check whether the current input is valid. code it in java.
write header file for sorting general element. it can sort any type of object(int,float,complex number, objects)
many irregular shape objects are moving in random direction. provide data structure and algo to detect collision. Remember that objects are in million.
At 5th round with director
one irregular shape is given. Provide algo to divide in multiple triangle
one system API available setOStimer(time n, function ptr, function arg)
it sets time for n sec. after expiration of timer it calls function.
if another timer set with setOStimer, it will erase previously sets timer.
Ex. at t = 0, setOStimer(5,fn,arg)
at t = 4, setOStimer(10,fn1,arg1)
now first timer removed.
Question is using this API, write own API setTimer(), it will use given API. So that it will not erase previously set timer.
I gave solution using min heap. as soon as min value become zero call given API.But he is not convince with my answer. Most of the time i feel that he is trying to confuse me, when i tried for any answer.
Because of 3rd round i am not selected
Adobe 3rd round question.
write program to find out stack growing upward or downward.
5) Can we crash a process before entering Main() function ?
I said possible and I give following two examples
example 1:
int *i = 0;
int j = *i; // I think here memory access violation since pointer 'i' pointing 0th address.
int main()
{
return 0;
}Example 2:
int i = 1 / 0; // here Float point exception or divided by zero exception.
int main()
{
return 0;
}Today I executed , above two examples and I am getting compile time error "Line 2: error: initializer element is not constant
" .
Can some one please tell me why I am getting compile time error ?
4) How to initialize Constant variables in class( or object).
example 1: throws error "uninitialized member 'myclass::i' with 'const' type 'const int'
"
#include <iostream>
using namespace std;
class myclass{
public:
const int i;
myclass()
{
i = 10; // here throws error
}
};
int main()
{
myclass m;
cout<<m.i<<endl;
return 0;
}example 2: below piece of code works fine .
#include <iostream>
using namespace std;
class myclass{
public:
const int i;
myclass() : i(10)
{
}
};
int main()
{
myclass m;
cout<<m.i<<endl;
return 0;
}Can some one please explain me , why second example works fine ? . why not first example ?
3) Littele Endian vs Big Endian ?
Sub questions:
1) which one decides endianess , Processor(CPU) or Operating System ?
2) There any standard ways to convert little endian data to big endian and vice versa .
My answer:
Linux is little endian and Solaris is big endian.
After that I said Processor(CPU) decides endianness of the machine. Intel processor supports little endian and SPARCV( Solaris) processor supports big endian.
He asked what about Solaris operating system with Intel processor ?. I said it is little endian.
Am I correct ?
2. write down Linux "grep" command code.
Input: file and a pattern
Eg.
$ Mygrep "siva*" names.txt
Output:
print entire line if it contains "Siva" word or prefix.
e.g:
"good bad siva is bad boy."
"sivabrtt gjfg"
After that asked me to write code to support regular expressions like "Siva*", "siva+venkat", "^siva".
1) Print tree in reverse Spiral Order .
Input:
1
/ \
2 3
/ \ / \
4 5 6 7Output: 4->5->6->7->3->2->1
Design a Connection Pool. It should allow to configure pool size. Should be thread safe. Which data structure you will use etc.
Write a program to print string in the following pattern -
If i/p is 'abc' then o/p should be 'abbccccccbba'.
What are the mandatory conditions when compiler synthesizes the constructors.
class Foo
{
int a;
public :
virtual void Fun1() {};
};
Class X
{
Foo f;
public:
X()
{
memset(&f,0x0,sizeof(f);
}
}
int main()
{
X x;
}
Is there any problem in this code snippet. if yes what are the problems.
How to determine if a number is a power of 2 or not?
Ans
if((num) && (!(num & num-1)))
{
cout<<"Power of 2"
}
//edited by gekko
Given nXm 2 dimensional array where each row is sorted and each column is sorted. write a function to return true or false if a given element is present in array or not(complexity)
Given a sorting order string, sort the input string based on the given sorting order string. Ex sorting order string -> dfbcae
Input string -> abcdeeabc
output -> dbbccaaee
Two robots land on the Moon. They can move only either left or right. Both the robots have same path(line of movement, as if they are on a railway track). Write an algorithm so that robots would meet
A simple algorithm would be make 1 robot go right and another to the left, this way they would meet. What be more efficient algo?
Numbers are represented using letter as in phone keypad. For ex 2->a,b,c 3->d,e,f till 9->w,x,y,z (0 and 1 are not represented by any letter). Print all the possible strings that can be generated from the given 9 digit phone number.
For ex 23 would generate 9 strings
ad,ae,af,bd,be,bf,cd,ce,cf
write a function which would return true if a given number is 1 less than power of 2.
Ex 3,7,15 should return true.
What is Deadlock? How to avoid Deadlock?
Given an nXn grid of integers, staring and ending cells , write an algorithm to find the path with highest value.
1) You can move right, left, top and bottom
2) You can visit a cell only once
Given an even sized array, you can partition the array into groups of 2 (not necessarily adjacent elements). write the algorithm to find least partition value and display partition groups.
Partition value of group = sum of both the integers in the partition
Least partition value= Highest partition value - lowest partition value
A consulting firm has many employees e1, e2, e3... en. Each employee can work at multiple client sites, i.e. a subset of c1,c2,c3... cm.
For each valid pair (e,c) where employee e works at client c, there are attribute-value list (a1,v1), (a2,v2).... like salary=$100, hours=40, priority=P2 etc.
construct a data structure that can efficiently perform:
public void set(emp, cli, att, val)
public List<AttributeValue> get(emp, cli)
public List<EmployeeClient> get(att, val)
You can assume all attributes and values are strings.
You can represent Employee and Client in any way you want.
Try to do better than O(mn) for both the get queries. Try not to denormalize your data structure too much.
Find the number that occurs most of the times in an array? How can this be done better if you can distribute the problem across machines?
wt is an output
int x=7;
s.o.p(x++ *++x)
s.o.p(x)
a question set is given to you and you have to generate(question numbers are in an array)
generate different set of question paper for k students .. basically he wanted me to shuffle the array i think
Given an array of integers, find out number of ways in which you can select increasing subsequences of length k(k<=n).
for eg array is 1 4 6 2 5 & k=3
then the answer is :- 1 4 5, 1 2 5,1 4 6, 1 2 6,
so ways are 5
he first made me to write a recurrence then asked me to memoize that
My interview questions were
1)Copy Constructor
2)Inheritance.
3)Polymorphism.
4)Stack vs Heap
5)Hash table.(Which data structure is used to implement it and why?)
Find out the first non-repeating character in a given input string?
Given 'n' no of sets and each set is of a variable size. Find out the cross product of these 'n' of sets.
For eg.
{1,2} , {3,4} , {5,6,7} these are the three sets.The cross product of these sets would be as below.
{1,3,5},{1,3,6},{1,3,7},{1,4,5},{1,4,6},{1,4,7},{2,3,5},{2,3,6},{2,3,7},{2,4,5},{2,4,6},{2,4,7}.
My interviewer asked me to write the code for this problem in C .
We have a webite with 5 Webpages {A,B,C,D,E}. Whenever a user accesses the website, the application logs an entry in the access_log file.
For example: user user1@amazon.com accesses Page A at Time T0, Page B at Time T10 and Page C at time T11 etc and User user2@amazon.com accesses Page B at Time T2, Page D at time T3 etc..
Here is the log file. (assume Ti< Ti+1)
User1@amazon.com, A, T1
User2@amazon.com, B, T2
User2@amazon.com, D, T3
……
……
user1@amazon.com, B, T10,
….
User1@amazon.com, C, T20.
…..
….
….
…
A good way to find out how users are accessing this website, we usually find out user access pattern. For the purpose of this problem we will concentrate on only patterns on size 5. Here is an example of patterns: Lets say user user1@amazon.com visited the website 10 times in a particular month pages visited in order of time are => A, B, C , D, E, A, A , A , A, A. There are 6 patterns of size 5 here. : ABCDE, BCDEA, CDEAA, DEAAA, EAAAA, AAAAA.
We need to find out the most common pattern of size 5 across all users of the website for a particular month.
Some more info for the solution:
# Assume website experiences 10 million page accesses a day.
# Assume website has around 2 million active users. i.e. during a month approx 2 million users will visit the website at least once.
# User access log file rotates every day. i.e. a new log file is generated everyday for the website. Log file format access_log_<DATE YYYY-MM-DD>
# You have been given only one host with a gigabyte of memory. And log files are available locally.
# you cannot create new files.
The solution with small memory footprint will be preferred.
Please do explain your choice of specific data structure as the preferred one and its time complexity
Design API for an LRU cache( possible public methods). Also, explain the best DS to use for implementing an LRU cache.
Inheritance/Polymorphism - Definition
Difference between overloading and overriding
Given a binary search tree find the its least depth.
Convert a two dimensional byte array to one dimensional int array - int[] convert(byte[][] b). Optimize for minimum space usage.
Given an array of characters (not sorted), how do you find the most frequent character?
Example:
{a b a c d} - Answer 'a'
{a b a b d} - Either 'a' or 'b' should work
{a b c d e} - Any character in the array
translate a binary tree structure to a file, a sequence, which should allow you to rebuild a same tree based on that file (sequence)
which one should be preferable from the following two nested for loops:
1.
for(i=0;i<100;++i)
{
for(k=0;k<10000;++k)
{
<lines of code>
}
}
2.
for(k=0;k<10000;++k)
{
for(i=0;i<100;++i)
{
<lines of code>
}
}
why?
What are the differences between malloc & calloc.
What are the differences between new (in C++) & malloc (in).
A consulting firm has many employees e1, e2, e3... en. Each employee can work at multiple client sites, i.e. a subset of c1,c2,c3... cm.
For each valid pair (e,c) where employee e works at client c, there are attribute-value list (a1,v1), (a2,v2).... like salary=$100, hours=40, priority=P2 etc.
construct a data structure that can efficiently perform:
public void set(emp, cli, att, val)
public List<AttributeValue> get(emp, cli)
public val get(emp, cli, att)
You can assume all attributes and values are strings.
You can represent Employee and Client in any way you want.
Try to do better than O(mn) for both the get queries. Try not to denormalize your data structure too much.
The scenario was something like that:
You have to create a graph in most efficient way from relationship of nodes read from txt file.
text file contains information like:
node_id weight node_id
node_id weight node_id
.....
// which means two nodes are connected with some weight. (undirected)
There are around 600K such information for about 65000 nodes.
Aim is to create a a subgraph for a given node_id. i.e for that node_id find ALL successor nodes with level mentioned i.e form a subgraph for that node.
He was looking for c++ code and most efficient algorithm.
Inputs are invited.
Code malloc() in C
streaming byte data coming which can be intergers or characters
you have to sort both the integers and characters with there index intact.
for e.g you have c6b2e4a
your sorted array should be a2b4c6e
why new returns and poiter to object while
void* operator new (std::size_t size) throw (std::bad_alloc);
it declration shows return type as void*
int main()
{
int i=10;
{
int i=100;
printf("%d", i);
}
}1.what is the output ?
2. what signifies "{" "}" in above code .
"{" "}" will it create new "Activation Record" ( or Frame) in Stack ?
In my current company I am doing development. I got SDET Microsoft (IDC Hyderabad) offer.
I am in conflict state, whether to accept SDET or not. One thing I can say, I am not interested in testing.
I think, if I enter into SDET role, I cannot come back to SDE role since other companies also offer SDET role ( after two years).
I inquired about role change from SDET to SDE in Microsoft and it is not possible ( or very rare).
After two years, if I want to change from Microsoft to new company, then every company will consider my profile for testing or SDET.
Do you know anything about role change from SDET to SDE ?
<round 3>
11. difference between Inline and macro functions.
sub question :
1) what happens if you apply inline on recursive function.
2) is there any Recursive Macro function ?
e.g
#define SUM(x, y) do{
SUM(x,y);
}while(0);is there any error ?
<round 3>
10. differences between
char *str = "SIVA" and char str1[]="SIVA"
sub questions:
1) where string literal i.e "SIVA" will be stored ( heap , stack, data or code segments) in above both cases.
2) char *str = "SIVA";
str[0] = 'f' ;
any error ? compile time error or run time error ?
3) char *p = (char *) str;
p[0] = 'f' ;
any error ? compile time error or run time error ?
<round 3>
9. Array A[n] it contains numbers from 1 to n but 1 number repeated. Find out missing number.
----------------------
I have not answered this question and manager not happy with my performance. THIS THE END OF THE BATTLE.
<round3 >
8.He asked me many Hashing questions.
Sub questions
1. What is hashing ?
2. you can write your own hash methods or you can use existing Hash methods in STL C++.
which one you prefer ? why ?
3. Write a Generic hash function & hash table , which should support all data types INT, FLOAT, STRINGS, and OBJECTS .
<round3> ( Manager round )
7. Check given tree is symmetric or not ?
e.g
1) Symmetric
1
/ \
2 2
/ \
3 3
2) non-symmetric
1
/ \
2 3<round 2>
6. Quadrant contains N points and all are + ve points ( I mean both (X,Y) are +ve values).
sub questions:
1. How you will store( or Data structure) N points to make look up( or search) easy.
2. Find out closest point (Pj) for a entered point (Pi).
Note: He asked me time efficient solution.
User can add extra M points later point of time. So your solution should be Scalable.
<round 1>
5. Reverse single linked list .
<Round 1>
4. Grid[n][n] contains letters from 'A' to 'Z' randomly. You have to print all possible words from grid.
You are allowed to move Left, Right, Up and Down ( no diagonal move).
Sub Questions:
1. Write down Dictionary_Lookup() function prototype. ( I no need to implement Dictionary_Lookup() but I have to write down possible return value and its arguments ).
This help us to find out traversed characters forming word or not.
2. Write down complete code to print all possible words in Grid.
<written test >
3.check whether given single linked list is palindrome or not.
e.g: 1->2->1 palindrome
1->2->3 not a palindrome
Note: Time efficient and without using any other data structures.
<written test >
2. Two sorted arrays A[X] and B[Y+X]. in B array contains Y sorted elements and B can accommodate A[] X elements.
W.A.P to Merge two arrays and store resultant in B[] array.
Note: Time efficient and space efficient solution
I appeared for the Amazon( Bangalore) Interview on 05-Feb-2011. I cleared written test. After that I gave 3 rounds of interview.
Note: They are going conduct interviews on 13-Feb-2011 also. There is a chance to repeat following questions.
< written Test >
1. Preorder string"NNLLNLL" ( or similar string ) has given to you. You have to construct binary tree.
Here 'N' means non -leaf node.
Here 'L' means leaf node.
Note: every node contains 0 or 2 childrens.
Given a sorted array write a program to find number of occurrence of a given number in nlongn time where n is the size of the array.
e.g if the array is {23,45,67,89,89,89,456,567}
and the given number is 89 the output should be 2.
Given a million 3D points, how will you find the 10 closest to the origin?
Given an array having integers with just one integer repeated thrice, how will you find out which integer is that?
wap to get the height of a BST?
what are threads and multi-threads?
optimize a code to reverse bits of a character n print it?
Difference b/w i3 and core 2 duo processor?
Implement a pattern matching dictionary using Trie?
Implement merge-sort?
write a function to find out the factorial of a number. it should also work for large numbers like 100!
Given a singly linked list with a pointer p pointing to some node(not the first or last node), how will you delete that node? You have no access to the head of the node.
Its been 2 weeks since my second phone interview and I havent heard back from the HR. What is in general waiting period for HRs reply at amazon.
You are given a 1D array of integers, such as:
int[] array = [3,4,7,2,2,6,0,9];
Suppose you need to treat this array as a 2D table with a given number of rows.
You want to sum the columns of the table.
another value for numRows is 4..in that case the resultant array would look like
what if numRows==4?
3 4
7 2
2 6
0 9
----
12 21
write up a function as follows:
int[] retArray SumColumns(int[] array, int numRows)
{
}
try to come up with a linear solution- no constraints on space..
this was a phone int q i got, i gave a linear soln with some hints from the interviewer..biggest lesson learnt, before giving fancy test cases, check for THE MOST obvious case, null input..very very important, cant stress enough!..all the best for your interviews
write a function that prints unique random prime numbers from a given range.
Give a detailed description and designing of a Card Game?
Find the 100 most frequently occurring words in a set of documents. Optimize.
What is the probability of rolling a 10 and an 11 before rolling a 7?
What is the probability of rolling a 10 and an 11 before rolling a 7?
Implement a Queue using a Singly Linked list where insertion and Deletion are O(1)
Code for tree traversal
Binary search
if you we want that at any given time only 1 exe instance should be running how can we do that?
If [a1,a2,a3...,an,b1,b2...bn] is given input change this to [a1,b1,a2,b2.....an,bn] , solution should be in-place
You have 2 entity which have many-to-many relationship. How would you implement tables? How many tables do you need?
If a function has a variable declared (say int a) and returns its address, what would happen?
Well, its an automatic variable and on stack. So, its bad. The question is :
Why does the compiler let you do this (and just give a warning)? Any scenario where this is required?
singleton object?
Reverse a string as per the words, not the entire reverse. eg; "I am Sam" --> "Sam am I"
Given an array of integers, all but one of which appears an even number of times, find the one integer which appears an odd number of times.
main(){
..
..
fork();
fork();
..
..
}Qestion: How many processes will be there in system after second fork gets executed?
I said 3 but the interviewer said it is 4 can anybody explain me
How to search a number among a lot of numbers. I asked if it is one time thing. Answer is yes. Then I did sequential search; Then he said how about search another one....
Then I said sort these numbers first and suggest binary tree.
Wrote down the binary search code
There are 7 coins; One of them is different. Give you a weight and 2 chances to try. Please tell which one is different. (I can't....Sigh. Then he told me the different one is heavier. Then I got the answer.)
Suppose there are 100 lights, which are all off. First round past them, turn all on;
Second round past, turn every other off;
Third round, turn every third on;
vice verse;
Ask the 100 round past, which light will be on?
Draw and explain the structure of one of my projects in my resume.
You have a set of states, and respective populations, how will you choose a state with probabilty exactly equual to proportion of that state’s population over the sum of population of all the states
What is the possible problem if Hash Table grows more than 30 gb (ignore problems like bad hash function )
Given a file and and API containing getline() to read lines from it, how will u print only the unique lines from it.
Given two Trees, how do you check if they are equal.
Implement a Poker Table in C/C++
Reverse a singly linked list
Write a program to print hello world without using semi colon
Write a function to print all unique partitions on n tht are of size m. eg: n=10, m=4. it should print 7 1 1 1, 6 2 1 1, 5 3 1 1, 3 3 2 2,, so on
Path to deepest 1 in a binary tree.
We have a binary tree (not a BST) made up of only 0s and 1s. we need to find the deepest 1 with a path from root made up only of 1's.
Look at the binary tree below and the corresponding matrix given.
Now write an algorithm to generate matrix for any give binary tree
a
/ \
b c
/ \ / \
d e f g
|a|b|c|d|e|f|g|
a|0 0 0 0 0 0 0
b|1 0 0 0 0 0 0
c|1 0 0 0 0 0 0
d|1 1 0 0 0 0 0
e|1 1 0 0 0 0 0
f|1 0 1 0 0 0 0
g|1 0 1 0 0 0 0
Given a binary tree, and 3 values A,B and C. write an algorithm to check if there exists a path from A to C such that B lies in the path.
Insert a node in a sorted Circular singly Linked List ?
Followup Question
1. When you need to insert the new node in head, optimize the code
Algorithm to solve Sudoku and implement the code
First remove all repeated consecutive substring with length 1, then delete substring of length 2 and so on...
Example : string is “abcabeccced”
After removing repeated substring of length 1: “abcababceccced” --> “abcababceced” (2 'c' are removed)
After removing repeated substring of length 2: “abcababceced” --> “abcabceced” (substring “ab” is removed)
and so on...
propose an algo for this...
Implement counting semaphore in Java.
Tell me about any projects that you have worked on?
What is encapsulation?
What is a virtual function? How does a virtual function work?
What is the difference between a process and a thread?
Give an unsorted array of integers A and and an integer I, find out if any two members of A add up to I.
For example:
A = < 3, 25, 9, 15>
I = 12 returns true
but I = 19 returns false.
Can you find the answer in O(n*log(n)) time?
Can you find the answer in O(n) time?
Given an array of numbers. divide numbers in 2 sets. such that difference between sum of numbers in 2 sets is min.
problem of binary matrix
Given a binary matrix of N X N of integers , you need to return only unique rows of binary arrays
eg:
0 1 0 0 1
1 0 1 1 0
0 1 0 0 1
1 1 1 0 0
ans:
0 1 0 0 1
1 0 1 1 0
1 1 1 0 0
Given an array of +ve and -ve integers, re-arrange it so that u have +ves on one end and -ves on other,BUT RETAIN ORDER OF APPEARANCE..
for eg,
1,7,-5,9,-12,15
ans=
-5,-12,1,7,9,15
do it in O(n) without using any extra space.
Given an array of size n wherein elements keep on increasing monotically upto a certain location
after which they keep on decreasing monotically, then again keep on increasing, then decreasing
again and so on. Sort the array in place in O(n) and using only O(1) extra memory).
Difference is Minimum
Algorithm to find the two numbers whose difference is minimum among the set of numbers.
For example the sequence is 5, 13, 7, 0, 10, 20, 1, 15, 4, 19
The algorithm should return min diff = 20-19 = 1.
Constraint - Time Complexity O(N) & Space is not a constraint [upto O(3N)]
Assumption - Sorting O(nlogn) & comparison of adjacent numbers is already known & is not an option. Try to keep it linear
How will you store frequently occurring numbers?
A question on sql query on employee database.
What is the difference between c++ and java?
Given 3 tables: Employee (empid, empname), Employee_timesheet(empid, no_of_hours, date), Employee_hour_rate (empid, hour_rate). Calculate pay check of all employees on monthly basis.
Merge 2 sorted linked lists into one
Find bugs in the following program---
Function is accepting a string and length of string and it is supposed to return number of occurrences of 'A' or 'a' ..
unsigned int occur(char *pch,unsigned long len)
{
int tmpvar=len;
int i=0;
int ret=0;
if(*pch==NULL || !strcmp(pch," "))
return 0;
do
{
if(pch[i]=='A' || pch[i]=='a')
ret++;
else
i++;
}while(i<tmpvar);
return ret;
}
Given 2 integer arrays of same size and are individually sorted. Find the combined median of both the array's numbers without sorting both the arrays into one. He wanted O(log n) complexity.
(This was asked for many of our friends also.)
Find Bugs in the following function-
This function accepts a string and its length and it supposed to return number of A or a present in that string-
unsigned int occur(char *pch,unsigned long len)
{
int tmpvar=len;
int i=0;
int ret=0;
if(*pch==NULL || !strcmp(pch," "))
return 0;
do
{
if(pch[i]=='A' || pch[i]=='a')
ret++;
else
i++;
}while(i<tmpvar);
return ret;
}
I have a class A which implements serializible and there are two sub classes B and C which extends A. I want clsss B not be serializible ? How can I achive it?
Asked me to give a datastructure for a Server and Application combination.
Ex:
A3 X
A2 0 X
A1 X X
S1 S2 S3
Servers can host multiple Applications.
2. Each server application combination can have different attributes and can have different values
ex: S1 and A1 has an attribute State and the value can be UP OR DOWN
Write a method with the following signature
GetServerApps(string attributename, string attributevalue)
Improve the performance
Implement an algorithm to print out all files below a given root node.
package file;
import java.io.File;
public class PrintFile {
private void printFile(File file){
File[] childFilesList = file.listFiles();
if(childFilesList !=null && childFilesList.length>0){
for(File childFile : childFilesList){
if(childFile.isDirectory()){
printFile(childFile);
}
else{
System.out.println(childFile.getName());
}
}
}
}
public static void main(String args[]){
PrintFile printFile = new PrintFile();
printFile.printFile(new File("C:\\Shared"));
}
}write a program to print in words the single or double digit numbers entered.(do not use switch case)
write a program to display the no. of 1,2,3,4...
lettered words in paragraph.
example:
1.search
2.engine
3.needs
4.to
5.fast
//output
search engine needs to be fast.
asked in interview ,though i didn't understand the purpose.
count the number of unique element in array of numbers in minimum time complexity.
There is a stream of numbers coming and u have to select any number at random. but u cannot save all the numbers , constant space complexity. how will u do it so that the probability of any number being selected is same
2 stacks are given, one is full of numbers and other in empty, one integer variable is given, fill the 2nd stack with
numbers in ascending order with space and time constraints.
Given a long string, arrange the words in alphabetical order, delete the duplicates and output the words with their frequency.
Write an algorithm to find a given substring from a string
Give test cases for a code that finds a power of a number.
Give an efficient algorithm to find the kth largest element.
How will you transfer a file across 2 hosts knowing the fact that the network connectivity is unreliable and very bad?
Given a webserver how will you handle load performance (eg the server can handle only 10000 connections at any point of time)
How will you find the center of a linked list?Explain complexity.
Write a c code to check if a given c syntax is correct (a small module of compiler)
What is virtual function?
Why Goldman Sachs.
Design ATM machine.
call by reference, call by value.
You have a student class which have String firstName, boolean isBoy and int age. Write equals method for the class.
I wrote it then he asked there is a class Student2 which extends from this and has lastName field as well.
Now
Student s1 = new Student("firstName", 23, true);
Student s2 = new Student("firstName", "lastName", 23, true);what will s1.equals(s2) will return. Is it correct ?
You have been given array of n numbers. Find min and mix. Give optimized solution and minimum number of comparisons.
What is difference between C and C++?
2 , 1, 7 , 8, 5, 3, 11, 10
Above are the stock price of a stock on different days . Given that you know these stock prices before hand, find how will you maximize the profit ? you have only 3 options ( Buy, Hold, Sell)
Write the sequence of steps that will give the max profit.
How will you free a object in C++ ?
Ans : delete(obj);
Now how is this different than free(); ?
What is difference between pointer and reference, and why do we not use pointers in C++ and use reference instead ?
. There are 3 people on a tower which may collapse due to fire. King(78 kg),Queen(42kg) and Prince(36kg).There is a pulley on the tower with baskets tied to it on both the sides of rope around the pulley. There is a 30kg stone in one of the baskets. There can be two persons or a person and a stone or a person or a stone in the baskets keeping in mind that the weight difference is not more than 6kg else rope would break. You have to bring all the three on ground safely.
Difference between set, list.
Quick sort, bubble sort, merge sort and their complexities
Print elements in level order in Binary tree
paragraph is given find out the second largest word in given space and time.
There is an array having 1 to 100 numbers randomly placed. But two numbers are missing from the list. What are those two numbers?(no hashing,no sorting)
//is there is better solution than taking sum and then difference from sum of all 100 numbers and then searching for all possibilities.
Onsite Interview: Given a tree, find out if the tree has a given sum or not.
Print all possible palindromes(of length >2) for a given string.
Onsite interview: Design the maze puzzle.. How will you set up an interesting puzzle for a User to solve..
Onsite interview: Given sorted doubly linked list, write code to insert and delete elements from the list..
Onsite interview: Given two strings, return the last index of a given substring in a string
first round screening at college: Given two arrays find intersection.. i discussed two approaches.. hash based and merge based.. was asked to talk about the complexities and explain when and why, which is better
Where are logical mistakes(minimum 3)
public class Test1 {
private int maxCount = 1000;
private int index = 0;
private Object[] objects = new Object[maxCount];
public void push (Object o){
objects[index] = o;
index++;
}
public Object pop(){
index--;
return objects[index];
}
}
Name all immutable classes in JAVA?
I know only 'String' class. Is there any other also?
How to sort ip addresses in JAVA? Is anyone can give me exact method?
I told we can use Comparator but interviewer was not happy with my answer.
Write an efficient algorithm for word count without using library functions(tokens.count, split etc). Also write as many test cases as you can around it.
Find the output of the following Program-
void main()
{
int array[4]={10,20,30,40};
int *tmp=array;
for (int i=0;i<4;i++)
{
tmp+=sizeof(int);
printf("%d",*tmp);
}
getch();
}
i think it should be 30 0 0 0
Compress a given string "aabbbccc" to "a2b3c3"
constraint: inplace compression, no extra space to be used
assumption : output size will not exceed input size.. ex input:"abb" -> "a1b2" buffer overflow.. such inputs will not be given.
Write a function to check whether the Binary Tree is mirror structure.
True
(A (B (C,D), E( F,G)))
or
(A (B (C)), D(E)))
False
(A (B))
or
(A (B,C(D,E)))
Two integer arrays, write a function to out pairs of number.
(The sequence is not important)
Ex:
input: [2,5,6,8,10,2,3,5] & [4,7,3,5,2,10,2,4] output:[2,2,3,5,10]
input: [2,2,2,3,4,5,6,7] & [2,2,5,5,7,10] output: [2,2,5,7]
I said saved the smaller array to hashmap (number as key, counter as value), and go through the larger array to generate pair by checking map.
Runtime: O(m) Space: O(n) ... m is larger array and n is smaller array
And, then he asked what if the device doesn't have much space to create map, then I said we should sort the array and use binary search.
Any better solution?
Ebay has its own system that it uses to levy taxes on the sellers. The taxes are computed in a progressive manner. For eg. if the seller sells goods worth $25 then for the first 10 dollars tax=8% and on remaining 15 dollars tax = 7%. So total tax= 8% of 25 + 7% of 15.
The table that they use to compute the tax is as follows
$0 - $10 8%
$11 - $50 7%
$51 - $500 6%
$501 - $10000 5%
$10001 -$1000000 4% and so on.
Which data structure would you use to store this table and how would you use that data structure to code a function
float computeTaxableAmount(float amount) {}
In Collection framework, why is external synchronization is faster than internal one(Vector, HashTable etc)? Even though they both use same mechanism?
Why do we need thread class when we have Runnable interface?
There is a row of houses in which each house contains some amount of money. Write an algorithm that loots the maximum amount of money from these houses. The only restriction is that you cannot loot two houses that are directly next to each other.
Write a function that rotates and MxN matrix. Even though the matrix is MxN, you are given it in the form of a 1 dimensional array.
int[] Rotate(int[] arr, numRows, numCols)
Does not need to be in place.
Print the nodes of a binary tree by level (breadth first)
Write the memmove function in C. Given two arrays a1 and a2, copy a1 in to a2. Beware aware of the fact that a1 may be overlapping a2 in memory.
How to tell whether a given number is lucky number,its definition can be found here :
en.wikipedia.org/wiki/Lucky_number
Similiar to memory barriers & conditional variable(used in multi threaded process) ,what can u do for multi process application?
HInt:IPC's is overkill.Think about file.
A game. 7 people in a circle, the third one will be deleted in each round. Use loop or recursive. How many loop and which data structure you will use to store these data?
What is a stack? Modified a program with indefinite loop
How to store a sequence of numbers according to frequency. The most frequent number stores at the beginning
What is a linked list; what is a hash map
How do you handle a confliction in a project. How do you divide the project within a team?
What is the difference between Java and C++
How to find an integer that repeats more than (>)n/2 times..in a given array of size n..in O(1) time complexity..
Note:Its not a sorted array.
Write recurssive fibonacci and print the value in order (eg 0 1 1 2 3 5)
What are basic structures that are considered in polymorphism in Java and how inheritance help in polymorphism?
What are basic structures that are considered in polymorphism in Java and how inheritance help in polymorphism?
Name all the memories which are available in JVM?
I knew only heap and perm. Is there any other memory also?
1. What is file system ?
2. How to recover if super block got corrupted?
1. How to find whether two link-lists intersect each other or not?
If yes find intersection point.
Given 2 strings S1 and S2, Check the first charaster that is repeated in S2.
Given array of n integers and given a number X, find all the unique pairs of elemens (a,b), whoose some is equal to X.
Two input strings is given, find out whether 2nd string is rotated of 1st string. e.g. string1="abcd", string2="cdab" should return true.
string1="abcd", string2="cdba" should return false.
A 2-D matrix having row and column sorted. How to search an element in given matrix.
I don't have questions but do not apply here if you have other offers. I am Epic's employee and they will tell you that you will work on C# but the chances of that happening is like 1% for the next 2 years. HTH.
Flood fill algorithm.
Bar Raiser : Determine all non concentric palindromes in a String.
I was asked this at a career fair by one of the recruiters and I think I gave a pretty bad answer for it (although the recruiter said he was happy with it). The question was having an integer array where there are repeating numbers and all but one repeat an even number of times. How would you find the number that repeats an odd number of times? He also asked if this can be done without using other data structures. (I think he said the array wasn't sorted).
I have a lottery ticket. Each of these lottery tickets has a 6 digit number on it. The winning lottery tickets are those whose sum of the first three digits is equal to the sum of the last three digits. How many possible winning tickets are there?
Note: Leading ‘ZEROES’ are counted. So a number like 004103 is a valid winning ticket since 0+0+4 = 1+0+3.
Find kth largest of sum of elements in 2 array .
Develop a mechanism for synchronising three hardware units while a accessing a shared hw resource.Use the available four signal types - high,low,negative pulse,positive pulse.Think of them as vertices of a triangle(with the edges as the physical interconnection amongs the hw units).Something like CSMA/CD
How will you efficiently bitwise reverse a very long character string efficiently(Dont use the typical bitwise swapping)
Given a long bit string M and a small bit string N
Make the bits between p & q in M same as N (q-p = strlen(N))
We have a web server that consists of a log file, which will be updated with the Visitor ID, who ever visits the website. It is a very large file, well formatted and delimited.
We should find all the visitor IDs who visited the website on that day. The constraints are we have 100 GB HD and 100 MB RAM. Virtual memory is not allowed. The time complexity should be less than O(n^2). You can use the whole of 100 MB RAM for any Data Structure.
Note: Consider the Log file is really big compared to 100 MB.
Given a dictionary find out if given word can be made by two words in dictionary. For eg. given "newspaper" you have to find if it can be made by two words. (news and paper in this case)
for 2 sorted arrays one with size X and another with size X+Y which has only Y elements. merge these arrays in to second array such that resultant array at end will be sorted.
A special type of tree is given, Where all leaf are marked with L and others are marked with N. every node can have 0 or at most 2 nodes. Trees preorder traversal is given give a algorithm to build tree from this traversal.
how you will design system for server and which will have many clients, all clients will keep of adding some words to system and server has to detect which words to accept, at the same time server will also keep on adding words.So which data structure you will use so that system will be efficient and fast.
There is a binary tree(Not a BST) in which you are given three nodes x,y,z .Write a function which finds whether y lies in the path b/w x
and z.
Given a stream of N integers which has the property that no integer is more than 1000 positions away from its sorted location, how would you output the integers in sorted order while using constant storage?
Give two dice - one is a standard dice, the other is blank (nothing painted on any of the faces).
The problem is to paint the blank dice in such a manner so that when you roll both of them together, the sum of both the faces should lie between 1 and 12. Numbers from 1-12 (both inclusive) equally likely.
When you are asked to tune the performance of a SQL query, list the checklist you would do.
Note: you cannot use index.
For any table, say order table, it was loaded some data double. Write a query to list the double loaded records with all columns and double primary key, but each double records only show once.
Table:
Order (OrderID, OrderDate)
OrderItem (ItemID, OrderID)
Query:
1. List all orders put yesterday.
2. How many items were ordered yesterday?
3. List all orders which order more than 3 items yesterday.
4. How many orders which order more than 3 items yesterday?
Write an 0(n) algorithm for detecting conflicts in appointments.
public class Appointment {
long startTime;
long endTime;
boolean hasConflict;
}
public static ArrayList<Appointment> markCOnficts(ArrayList<Appointment> apntmnts)
//your code here..for each appointment if it
//has a conflict you need to set hasConflict
//parm = trueOpen ended question:
In Google apps or google app engine google limits the rate at which an application can fire queries at google systems(e.g. REST or any other API calls). This rate is determined dynamically by Google and it is changing continuously changing. Devise an algorithm to determine the optimal rate at which applications can fire requests (calling google APIs).
Note: for simplicity lets assume that
1. if application exceeds the rate limit Google returns 503
2. and return 200 for successful API call.
Write a method to return the index of first out of order letter in input string
Given the current board configuration of "Game of Life" game, write a method/function to next generation board configuration.
Note: search "Conway's Game of Life" wikipedia for rules
Input: 2D array int[][]board,
board[i][j] = 1 if cell at i,j is alive
board[i][j] = 0 if cell at i,j is dead
Problem:
public static int[][] nextConfig(int[][] board) {
//code to calculate next board configuration
//return new config
}Given a directed graph G, write a program to detect the cycle in it.
What are virtual methods? An example use-case for having a virtual destructor with a small code snippet showing that case.
Given n, tell nth Fibonacci number. Both recursion solution and then he asked me to improve the performance (loop solution)
In a TicTacToe game, if you are given a particular state of player 'X', assuming that he and the other player makes perfect moves from then on, how would you tell if he would win or lose or draw ?
How do you test a keyboard
Tell me the sequence of TCP socket function calls at server side.
What is the difference between malloc () and calloc ()?
First the interviewer have called me on time, he introduced himself and his project which takes about 10 minutes, then he asked me why do you want to join facebook..
Then he started in the technical questions, the first questions was:
he described to me a game called othelo (http://en.wikipedia.org/wiki/Reversi) which is a 2 player board game using for example X and O, if player X placed X in an empty space
_OOOX
the O's between the two X's will be converted to X
XOOOX ==> XXXXX
this will happen on the current row, column, and the two diagonals in every directions
and if the following case happened
__OOX
and the X player placed X in the first space
X_OOX
nothing occured for the two Os
given a certain state of the board, location on the board, a certain piece
to place on the given location
update the board, and make the required validations
Then I started to code the required method, then have revised it and fixed small bugs, then he told me that it seems to be working.
then we turned to the second question:
which is given a Collection<String> words, return a Collection<String> of anagrams found in the given collection for example "The rat fell in the tar" => returned [rat tar]
Then I have discussed him in an algorithm with O(n k lg k) where n is the number of words and k is the average length of the word, then I started to code it and then he said that it seems to be working.
then the interview is finished.
Notes:
* Try to practice a lot before the interview, by solving such problems and try to mimic the interview environment by coding in the collabedit.com text editor
* Don't use Ctrl + S while coding in collabedit as it may lead to some problems.
* Don't be afraid before the interview, just calm down as the interviewers are very friendly.
Good Luck :)
What am I allowed to assume about the initial values
of variables which are not explicitly initialized?
A: Uninitialized variables with "static" duration start out as 0,
as if the programmer had initialized them. Variables with
"automatic" duration, and dynamically-allocated memory, start
out containing garbage (with the exception of calloc).
How do I declare an array of N pointers to functions returning
pointers to functions returning pointers to characters?
A: char *(*(*a[N])())();
Using a chain of typedefs, or the cdecl program, makes these
declarations easier.
5: What am I allowed to assume about the initial values
of variables which are not explicitly initialized?
3: I can#4051t seem to define a linked list node which contains a
pointer to itself.
A: Structures in C can certainly contain pointers to themselves;
the discussion and example in section 6.5 of K&R make this
clear. Problems arise if an attempt is made to define (and use)
a typedef in the midst of such a declaration; avoid this.
2: What#4051s the auto keyword good for?
A: Nothing.
1: What does extern mean in a function declaration?
A: Nothing, really; the keyword extern is optional here.
Assume you have a set of 1500 independent pieces of code. We'll call them projects. Each project can either be:
1) completely independent
2) dependent on other projects
3) dependent on other projects and have other projects dependent on it
The combined build times of all 1500 projects is 24 hours(so build project 1, when it finished, build project 2, etc). A build consists of compiling and linking all the requisite code. You can assume you don't have to worry about a budget. If there's a tool that would help you out, you can use it if you can describe how it works. How would you speed up the build process?
how to serialize and deserialize a n-ary tree?
Given a matrix m(i,j) such that m(i,j) gives the distance b/w i_th and j_th station . You are at a given station and need to go some other given station with least travelling distance .
Input: A unsorted array of size n.
Output: An array of size n.
Relationship:
> elements of input array and output array have 1:1 correspondence.
> output[i] is equal to the input[j] (j>i) which is smaller than input[i] and jth is nearest to ith ( i.e. first element which is smaller).
> If no such element exists for Input[i] then output[i]=0.
Eg.
Input: 1 5 7 6 3 16 29 2 7
Output: 0 3 6 3 2 2 2 0 0
What intern method does in java?
class A{//..};
class B1:public A{//..};
class B2:public A{//..};
how to cast A part of B1 to A part of B2
Implement a queue in which push_rear(), pop_front() and get_min() are all constant time operations.
write a Java program that reads this file, sort the lines of the file using a reverse
dictionary sort, then print the results to stdout. Send the answer and
attach the text file you used for testing.
I was asked this question in a recent interview...could somebody tell me how to solve this one...
write a function which sorts an array of strings based on their reversed representation.
(Reversed representation means a string in reverse order: foobar => raboof)
Example: ["xxxB", "yyyC", "zzzA"] => ["zzzA", "xxxB", "yyyC"]
Note: The strings are not reversed in the result. They're just sorted based on their reversed representation.
Telme about your work experience and challenging projects.
Write code to evaluate the value of e^x using the Taylor;s series.
The series was given.
An O(n ) solution was expected with no Overflow.
1. A
2. Ctrl+A
3. Ctrl+C
4. Ctrl+V
If you can only press the keyboard for N times (with the above four keys), please write a program to produce maximum numbers of A. If possible, please also print out the sequence of keys.
So the input parameter is N (No. of keys that you can press), the output is M (No. of As that you can produce).
write a program to Reverse the sentence in the following order specified
i am an indian
am an indian i
an indian am i
indian an am i.
My last round was pretty simple in which he wanted a depth first traversal of a tree for which i gave him the preorder traversal..
I had time left in this round so he gave me another problem in which I was given a triangle class and he asked me what were the interesting cases where there arises a possiblity that the code may break.
My answers were tri(int a ,int b,int c)
-Niether of sides shd be 0
-sum of two sides greater than the third.
-No side shd be greater than INTMAX and also if a = INTMAX -6 , b = INTMAX -6 , c = 20
For this case there may be an int overflow so i told him that instead of checking for a+b>c we could check whether c> a-b, so that there would be no overflow.
I thought I had done my interview well and was confident i would be selected but I donno what happened they rejected me.. But it was a great experience....
My third round question was
How do you find the 3rd largest word in a given string that is millions of characters long and he wanted me to give a solution in only one pass ?
I gave him a solution with arraylists and he was like it is too expensive using them .
Then i gave him a solution to find in a single pass in the same way we find the third largest number in a set of intergers ..
My second round question was
How do you check if two pixels are overlapping or not.. ?
I gave him the algorithm for the case where two rectangles overlap..
My first interview question was
How do you find the longest palindrome in a given string ?
I gave him a O(n^2) algorithm but he was keen on me giving a O(n) one..
Had an onsite interview with Microsoft on 17th Dec .. Accommodation and travel was provided and they make sure that the interviewees are in their best spirits before the interview.. I was listed to be interviewed with the windows windows live group for DEV and mine started at 8.00AM in the morning and I was scheduled for 4 interviews each of which were 45 mins long.. Did not land into the job though but it was a great experience as this was my first interview.. The interviewers were really nice and helped a bit whenever i was stuck..
The height of a tree is defined as follows:
The height of a terminal node is 0.
The height of an internal node is 1 + the maximum of the heights of its children.
Suppose it is specified that height() will only be called on InternalNodes.
Consider the following a implementation of InternalNode.height(), with no implementation in either Node or TerminalNode?
int height() {
int lheight = (left == null) ? 0 : left.height();
int rheight = (right == null) ? 0 : right.height();
return (lheight > rheight ? lheight : rheight);
}
Which, if any, of the following are problems that will cause the above code to fail:
A.It won’t compile because there is no definition (concrete or abstract) in Node.
B. 1 should be added to the value of the return
//options:
a)The code is correct as is.
b)A: it won’t compile, but if that were fixed it would work and produce the correct result.
c)B: it will compile but produce the wrong result.
d)Both: it won’t compile, and even if that were fixed, it would produce the wrong result.
rearrange an array of integers such that on one side you have all even numbers and the other side you have all odd numbers.
now among the even numbers, they should be sorted and among the odd numbers they should be sorted
find max and min in an array with the least number of comparisons
how do u remove duplicates from a list.
1. list is sorted
2. list is not sorted
find all permutations of a string
how do you know if a tree is a bst or not
design a data structure for a DNS server
you are given a bst where each node has a int value , parent pointer , and left and right pointers , write a function to find a path with a given sum value. Path can go from left subtree tree , include root and go to right tree as well . we need to find these paths also .
5
/ \
1 10
/ \ / \
0 2 6 11
so to find 16 we say it is 1 to 5 to 10
write down String class copy constructor ?
find a bug in following code :
class A
{
public:
static int i;
void print()
{
cout<< i << endl ;
}
};
int main()
{
A a;
a.print();
}I run above code, and I am getting "ndefined reference to `A::i'" . Why I am getting this error ?
Suppose you have a map like this
map<key,value>.It is easy to find a key and update its value.But can you find a specific value and update its key assuming all key,value pairs are unique
You Have File of Containing 1 Million Integers You need To Find 10
Maximum Integer Out of Them.How You Will Do That ...what is Time &
space Complexity of Algorithm that you will use....
Round-I Write a function that takes an array of five integers, each of which is between 1 and 10, and returns the number of combinations of those integers that sum to 15. For example, calling the function with the array [1, 2, 3, 4, 5] should return 1, while calling it with [5, 5, 10, 2, 3] should return 4 (5 + 10, 5 + 10, 5 + 5 + 2 + 3, 10 + 2 + 3). You may assume that the input has already been validated.
Asked about BFS algorithm. And then he asked about the approach of how do you print the all left nodes, then all leafs and then all right nodes of a binary tree.
How will you rotate a given matrix? Question from CC book.
If given a position (x,y) of knight on a chess board, how will you determine all the valid moves that a knight can move. I coded the function on the while board by using a helper function IsValidMove(x,y)
Implement the circular queue? Interviewer was looking for complete requirements and design I would consider before implementing the queue.
Write a function which determines whether provided string matches specified pattern. Signature:
bool is_match(char* text, char* pattern)
Pattern can contain any characters + '*' character which means zero or more characters. For example: is_match("hello", "h*o") returns true; is_match("hello", "hel*lo") also returns true.
I recently got screwed up at Red Hat Interview.
Here is the question they asked me
Write C program to take directory name as command line argument and
print last 3 directories and 3 files in all subdirectories without using
api 'system' inside it.
suppose directory dir0 contains
dir1, di2, dir3, dir4, dir5 and file1, file2, file3, file4, file5, file6
and
dir1 contains dir6 file7 file8 file9 file10
program should output -
dir3, dir4, dir5, file4, file5, file6, dir6, file8, file9, file10
I could only make upto directory scanning.
If some one wants to discuss the solution then welcome.
Given a random function that generates a random number between 1 and 5 inclusive, write a function to generate a random number between 1 and 7 inclusive.
what is fast retransmit? explain with example?
what is SACK? what is the use of SACK?
when we type in google for seach it will genate search text. for a stream of searchtext how you will find most 10 frequent search test. give a efficient data structure for this. and also solve it with possible minimum complexity.
Find loop in a single list.
proof the correctness of your algorithm.
if fast pointer incremented by 3 and slow pointer incremented by 2 would it work? proof the correctness of second strategy?
which one is more efficient and why?
what is Virtualization? give an example of Virtualization.
Write a program which print all possible combination of 10 A and 10 ‘B’
write a program which find LCA of a binary tree. It is not a BST
1. concept of TCP and UDP and use case.
2. serialize and deserialize.
say given ab,cd,fgh, output a single string
given that single string output ab,cd,fgh
string serialize(string str[], int n)
{
string result = "";
if(n < 1)
return result;
for (int i = 0; i < n; i++)
{
result += "\"";
for(int j = 0; j < str[i].length(); j++)
{
if(str[i][j] == '\\')
{
result += "\\\\";
}
else if(str[i][j] == '\"')
{
result += "\\\"";
}
else
{
result += str[i][j];
}
}
result += "\"";
}
cout<<result<<endl;
return result;
}
void deserialize(string str)
{
if(str == "")
return ;
string token;
bool doubleQuoteBegin = false;
bool skip = false;
for (int i = 0; i < str.length(); i++)
{
if(str[i] == '\\' && !skip)
{
skip = true;
}
else if(str[i] == '\"')
{
if(skip)
{
token += '\"';
skip = false;
}
else
{
if(doubleQuoteBegin)
{
doubleQuoteBegin = false;
cout<<token<<endl;
token = "";
}
else
{
doubleQuoteBegin = true;
}
}
}
else if(str[i] == '\\' && skip)
{
token += '\\';
skip = false;
}
else if(str[i] == '\\' && !skip)
{
skip = true;
}
else
{
token += str[i];
}
}
}
Find two elements in an array whose sum is closest to zero??
given a set of distinct integers {a1, a2, a3, a4, a5, ...}
and a set of exclusion rules: R = {{a1, a3}, {a2, a4, a10}, ...}
can you print out all the valid subsets?
Example:
what is a valid subset? {a1, a4}
what is an invalid subset? {a1, a2, a4}
How to implement inheritance in C?
How to implement Virtual functions in C?
How to delete the duplicates in a Binary Tree?
Description:
eg. Tree
A
B C
D.C -.F
FH
output:
A
B C
D.H -.F
Here C & F are repeated. If a node value is duplicated, the duplicated value which comes later in the BFS of the tree should be eliminated, its left/right child should be linked to the deleted node's parent (if the children are not duplicated values).
Given an array A[1..n](range 0 to k). Divide this array into two subsets S1 and S2 such that
min{sum(S1)-sum(S2)}
perform divide operation without using "/" ... give the most optimized solution
How would you print the solution of longest increasing subsequence ??
How to compare two version numbers?
E.G. 1.2.30.112 @ 2.12.11.09
Code should be in java
sizeof(void)?
Implement a deck of cards using OOPs
What is a deadlock ? WAP in C++/C to remove deadlock
discuss the client-server architecture?
DIVIDE TWO VARYING LENGTH NUMBERS
EX: ONE CAN BE UPTO 60 DIGIT AND OTHER 40 DIGIT
How will you select all name,salary of all employees having 4th highest salary from Employee table.
A program has two functions 'reader_func' and 'writer_func'. The reader_func reads shared data and contains a critical section. The writer_func writes to shared data and contains a critical section.
Reader threads call reader_func. Writer threads call writer_func.
The condition is multiple reader threads can access the critical section at the same time as long as they don't access the critical section along with a writer. Only a single writer thread can access the critical section, i.e. no reader or other writer threads are allowed.
Give the code segment, add code that uses mutexes that controls access to the critical sections so that the shared data is not corrupted and satisfies the give conditions. You can create as many mutexes and global variables as you want. Don't emphasize too much on syntax as to how to acquire and release locks on mutexes. Just use mutex.acquire() and mutex.release() .
Code segment:
void reader_func()
{
//critical section
}
void writer_func()
{
//critical section
}Given an array arr of size M containing distinct integers, randomly select N distinct integers and output them. You are given the rand() function and N < M.
How to write a stub for unavailable server?
A application uses different its own server and some external, third party server also. Suppose if external or third party server is unavaiable, how will you test application?
What will be the approach to test the application when you are not getting third party server?
When would a teleportation device not increase the speed of your commute?
How would you test a Elevator?
Explain one of your project you have done in your past and what challenges did you face in that? If given one chance what would you like to change in the project you worked on
Why Microsoft? Why did you choose this major for Masters. what are good coding practice? How do you grade yourself as a coder/programmer.
Convert an ASCII representation of a positive integer to it's numeric value
A large file containing strings. How do you find number of unique strings? Write code...
FOLLOW UP: What hash function would you use?
FOLLOW UP: If hash cannot fit in the memory, what can you do...assuming only one machine.
FOLLOW UP: What if external sorting is also expensive...?
Sort an input string according to the given order string. There might be characters in input string that are not present in the order string and vice-versa. The characters of input string that are not present in the order string should come at the end of the output string in any order. Write code...
Example: Sort("abdcdfs","dacg");
output: ddacfbs
Given a sorted array with duplicates and a number, find the range in the form of (startIndex, endIndex) of that number. For example, given 0 2 3 3 3 10 10 and 3, return (2,4). Given the same array and 6, return (-1,-1).
Upon further probe:
1. Do better than linear scan, which is O(n). 2. You can just work out how to find the start index, and I will assume that you know how to find the end.
Reverse the order of words in a sentence in place. e.g. Convert "A quick brown fox" To "fox brown quick A".
Find the minimum depth of a binary tree
find next palindrome of a number.
eg 125 next palindrome is 131
write a program to reverse words in a sentence..do it in a single pass..!!
6. Using the basic string operations length, concatenate, copy, and find, develop a recursive algorithm for reversing a string.
5. Contrast Public, Private, and protected inheritance.
4. Construct the Huffman Code for the C+ keywords and weights given in the following table:
Words Weight
int 0.30
main 0.30
while 0.05
if 0.20
for 0.15
3. Search a graph for a vertex that stores a given data item, and retrieve information about that item and/or update the information.
1. Construct the Huffman code for the following table of letters and weights:
Character Weight
a 0.20
b 0.10
c 0.08
d 0.08
e 0.40
f 0.05
g 0.05
h 0.04
2. Using Huffman code developed for answer 1, encode the message "feed a deaf aged hag".
We have a table with two column name and marks. Write a query based on this table which returns grades like if marks if greater than 700, it will be 'A' if it is less than 700 and greater than 500, it will be 'B' OR it will be 'C'. Main point table has only two column.
If possible please, give me whole query.
Thanks.
Given a very large array of n integers, find the kth largest value in the array efficiently. You may assume that k is much smaller than n.
e.g. the third largest (k=3) of [1,3,2,2] is 1, not 2.
Write a function to convert Hex to Dec
int ConvertHexToDec(string)
Phone screen:
45 minute interview. Horrible experience:
1. How do you call a C library from C++ code and how to you call a C++ library from C code? In the second one, the C++ library only contains pointers and normal function calls, nothing C++ related.
I didn't really know what he was looking for in the second case but then he gave me function overloading as a hint. Then mentioned name mangling.
2. You have an empty class. What does compiler do?
3. What if the class had 1 object? Then he asked if these objects can be sorted? (Sorry, I don't get it either.) When I said you can't sort 1 object then he switched and said an array of objects.
4. Can you sort these objects in the class as a key to a map?
5. What's the sorting order of a map?
6. You have a singly linked list from 1 to 10. and your pointer is pointing to the 5th element. Oh and you don't have a head or tail pointer. Tell me the algorithm to delete this element.
Sorry I don't remember some of the other ridiculous questions. :(
Phone screen:
45 minute interview. Horrible experience:
1. How do you call a C library from C++ code and how to you call a C++ library from C code? In the second one, the C++ library only contains pointers and normal function calls, nothing C++ related.
<Round 4>
with manager:
Car design Problem
and many HR type question checking ur behavior and practices you follow while work,coding testing etc.
<Round 3>
How to preprocess dictionary so that below operations are best supported
a) search in dictiorry
b) given a string find all valid anagrams in a dictionary
c) typing prefix of a valid string suggests valid words
<Round 3>
How to send one class object from reciever to sender
<Round 3>
prove that n(n2-1) is div by 24
Note: n is odd and >=3
<Round 3>
Search in a rotated array
<Round 2>
Given a list of string,usingjust single bit mask,find the repeated elements of strings..
but not allowed to change the mask after processing each string.
Hint u can use single extra bit.
<Round 2>
Product puzzle..but constraints no extra buffer..
<Round 2>
Merge k sorted lists into a single sorted list.Time complexity.Space complexity
<Round 2>
Given an array having n/2 distinct and n/2 unique elements..find the minumum comparisions to find the repeating number.
<Round 2>
Design twitter like system where only two operations are allowed..
1) PostMessage(Reciever,Message)
2) GetallMessageofUser(User)
<Round 2>
WAP to Reverse every k nodes of the linked list
<Round 1>
WAP to rotate the array by position n.
<Round 1>
WAP to find intersection of two LL.
<Written>
WAP to alternate merge 2 LL.
<Written>
WAP to find cycle in a directed graph.If multiple cycles are found print any but starting with the smallest node no.
Write a function to find the depth of a binary search tree
Round 5: with Director
Write a function to get lowest common ancestor in "binary tree"
Round 4:
write a insert function to insert into binary search tree node *insert(node *root);
Follow up :
Whats the problem with this ?
Ans: skewed tree for sorted inputs
Discuss algo that will avoid this ?
Round 3:
write a function that output the size of highest sub square matrix of 1s in matrix of 0s and 1s
For ex:
0 1
0 0 output 1
0 0 0
0 1 1
0 1 1 output 2
}}}
Round 2 :
Write a code to print level order traversal of N-ary tree
data structure can be assumed as
class Node{
vector<Node> children;
int val;
}Round 1 :
suppose you are given a function void NumberofSum(int n) , write a code such that will print all the numbers that will sum up to n
For Ex.
n output
1 {1}
2 {(1,1) , (2)}
3 {(1,1,1), (1,2) , (3)}
4 {(1,1,1,1),(1,1,2),(1,3),(2,2) , (4)}Write a program for deck shuffling. And make sure that no card will get the same position as previously. i.e. after shuffle all card should have different position.
Consider you have to create a OO design of a card playing games. This system needs to be very generic so that you can reuse for any card game with minimal change. Specify all classes and functions
Mirror of Binary tree without recursion.
Input: Array of integers, A[0], A[1], ..., A[n]
An operation is defined to have all A[i] altered by 1, i.e., A[i]++/A[i]--. Note whether A[i] is increased or decreased is independent from other elements in A.
Question: return the minimum number of operations to make all elements in A[i] be equal. If it is impossible, return -1;
Given N arrays containing values between 0 to x, what data structure would you use to store these arrays so that when given a test array 't' find the closest array in N that has highest number of elements in 't'? Also what algorithm would you use to find the closest array. N could be in the order of 1000. x could be between [100,1000]
Implement the following function, FindSortedArrayRotation, which takes as its input an array of unique integers that has been sorted in ascending order, then rotated by an unknown amount X where 0 <= X <= (arrayLength - 1). An array rotation by amount X moves every element array[i] to array[(i + X) % arrayLength]. FindSortedArrayRotation discovers and returns X by examining the array. Consider performance, memory utilization and code clarity and elegance of the solution when implementing the function.
how i Develop c/c++ program that read a file specified by the user, then provides a menu of choices to be done using the specified file as follows:
Enter what u what to do with the file:
1.Compress the file.
2.Search for a pattern at the file
3.Read the file (display the file content at the terminal)
4.Eject the program
have to use the fork system call mechanism to create a new child that handle the choices ,for example the parent process would read the file and if the user choose 2 a new child process will handle his request overwriting its parent code then invoking “grep” built in command
Write algorithm to return change in denominations of 10$, 5$, 1$, 25 cents, 10 cents etc..(See question posted by Anonymous on April 23 2010)
Replace all single occurrences of "a" with "the" (See question posted by Troy on Oct 7 2010)
Find no. of days between Jan1st and entered date (See question posted by Troy on Oct 7 2010)
interview:
Implement run length encoding and decoding.
Input:
aabbccaa encode:2a2b2c2a decode will be the input
Input: abcd encode:abcd decode:abcd
input:3122a encode:3122a decode:3122a
etc.
test atof(char *s)
written test:
print all the leaves of a binary tree(may not complete) as a link list.
1
/\
2 3
/\
4 5
output as a list: 4->5->3->NULL
How do you test a function which would return the second smallest number in a BST?
Bangalore written test
fucntion prints given 2d array in spiral fashion. give all test cases to test it
Bangalore written test
remote server is running on some port.
give test cases about get filename command
which returns response in format
filename filecontent
String s1 = bacdeg
String s2 = bcdaeg
write an algorithm which will return position of first character of string s1 that is appearing in s2
here postion of 'a' in string s2 as it is the first character of s1 that is coming in s2
Given array of integers and a int variable say X. Need to find out all unique pairs from array which sums to X.
for e.g. arr[] = {1,2,3} , X=4
output - (1,3) (3,1)
Bangalore written test
C function was given to find out the occurance of character "A" from an array. Need to find out the bugs in program.
working of a browser? -> parsing of html or xml content, how it works exactly?
Define static, virtual destructor?
Code for tic tac toe
what are the internal structure of STL's set and map. Why is that so efficient.
How to design a connection pool or object pool, How to design a inmemory LRU ( least frequently used ) cache in C++
We had a written test 1 30 min... 15 quant, 15 SQL, 20 c++, 2 design case study ( DB-design a database to maintain a school, C++ - implement a Doubleton class, get_instanc() should return alternative instances on every call )
why we can't create a base class pointer pointing to a derived object in case of private inheritance. for ex:
class base {};
class der : private base {};
int main()
{ base* b = new der; <<<--- fails
}
How would you write a spellcheck program that would highlight misspelled words as you typed?
How would you find a number in a dataset of unknown size?
Using the first Huffman code given
A= 01,
B = 0000,
C = 0001,
D = 001,
E = 1,
decode the following bit strings.
1. 000001001
2. 001101001
3. 000101001
What is SOAP, XML used for?
Generate all 6-bit binary values that has exactly 3 1s in it.
Generalize it for N-bit values with P 1s.
Phone interview:
45 minute interview... He seemed to have some set of questions but depending on my answers he kept asking more and more. Choose your topics wisely.
Describe a class you wrote.
Have you ever used any designed patterns? If yes, explain what it does and how it is used.
-I picked singleton so he made me explain what is private and public for this class. Why do we need a private constructor?
What is factory method?
This is where "virtual constructor" came up. He asked me if we can have one of those why and why not?
What needs to happen with a base classes destructor? (I think he was trying to get virtual destructors out of me.)
why do we need a virtual destructor?
how do you list the processes on a linux system?
what is context switching?
how do 2 threads communicate/share info?
what's a virtual table?
given map, hash table and linked list, which one is the fastest for seaching?(seach complexity)
how does a hash table work?
how does map work?
How can we generate all possibilities on braces ?
N value has given to us and we have to generate all possibilities.
**Examples:**
1) if N == 1, then only one possibility () .
2) if N==2, then possibilities are (()), ()()
3) if N==3, then possibilities are ((())), (())(),()()(), ()(()) ...
Note: left and right braces should match. I mean )( is INVALID for the N==1
How can we solve this problem by using recurrence approach ?
Question on Tree Data Structure: How can we fill all inorder successor pointer of all tree nodes ?
Tree node contains 3 pointers *left, *right and *Successor .
Struct node{
int data;
struct node *left;
struct node *right;
struct node *successor;
};A
/ \
B C
/ \ / \
D E F GINORDER Traversal: **DBEAFCG**
**Note:** A inorder successors are F,C and G.
**Function prototype:** void FillSuccessorNodes( struct node *root);
Tree's root node given to us and we need to fill successor pointer for all nodes.
case 1) some of the Successor pointers may be **NULL** . This case you have to fill that pointer with immediate Inorder Successor.Example: if A->Successor == NULL, then fill A->Successor = F
case 2) some of the Successor pointers may already points to correct successors. This case You no need to modify successor pointers.Example: 1) A->successor = F is valid
2) A->successor = C is valid
3) A-successor = G is valid . All these three cases you no need to modify successor pointer since these already pointing to correct successor nodes.
case 3) Some of the successor pointers are **not NULL** but these pointers pointing to INVALID successors i.e it could be inorder successor or some garbage value. This case you have to fill these nodes with immediate successor nodes.Example:
1) A->successor = B is invalid since B is not successor node , so we have to correct it to A->successor = F.
2) A->successor = 0x23237463478 is invalid since it is pointing to garbage value. So we we have to correct it to A->successor = F.
**1) Interviewer asked me time efficient solution in O(n) time complexity. Extra space allowed.
2) she gave some hint i.e we can use HASHing.****If you know the solution for this problem, please let me know .**Given a unordered array of numbers, remove the fewest number of numbers to produce the longest ordered sequence. Print count of fewest numbers to be removed, and the remaining sequence.
For example, if input is 1 2 3 4 5 6 7 8 9 10, no (zero) numbers are removed, and input is the longest sequence.
If input is, 1 2 3 8 10 5 6 7 12 9 4 0, then fewest number of elements to be removed is 5 is the fewest number to be removed, and the longest sequence is 1 2 3 5 6 7 12.
find triplets in an integer array which satisfy a[i]^2 + a[j]^2 = a[k]^2
What member function are given by compiler if we are not defined in the class?
What is conversion operator?
What is conversion constructor?
you are supposed to write a crontab enrty using a shell script... that means the shell script must trigger the crontab to make an entry...
you can take any cron job for example delete all .html files present in /var/www/myfolder
Given a positive integer n, write a function to print the nth row of Pascal's triangle.
Design and implement APIs for caching web pages.
Write a program to print out all valid tic-tac-toe game moves.
There are 8 bottles, one has poison. What's the minimum number of rats you need to find the poison bottle in time T, and how? (You get the rats you need all at once, feed them all at the same time, and poison kills them after time T.)
Class B
{
int b;
Public:
Void disp();
Void show();
};
Class D : public B
{
int d;
Class
Public:
Void disp();
Void show(D &);
};
What is the size of the Base Class and Derived
Class B
{
Public:
Void disp();
Void show();
};
Class D : public B
{
Public:
Void disp();
Void show(D &);
};
What is the size of Base Class and Derived Class?
Class B
{
Public:
Void disp();
Void show();
};
Class D : public B
{
Public:
Void disp();
Void show(D &);
};
int main()
{
B *b = new D();
b->disp();
b->show()//base clas show will be called
*/b->show(D)how call derive class show? */
}
how to call Derived class show function with base class pointer?
class Sample
{
public:
Sample() { cout<<"const"<<endl; }
~Sample() {cout<<"destr"<<endl;delete this; }
};
int main()
{
Sample *obj = new Sample;
delete obj;
return 0;
}
what happens when u delete this in destructor?
Implement Stack using Queues?
Write an SQL query to select the nth row from a table.
I asked the interviewer that, can I assume say the nth record is based on a primary/unique key column or any column, he said no, the question is just select the nth row.
If you were asked to design an efficient elevator system for a 100-storey building, enumerate the list of questions you would ask that you feel would be important to get answered before you start your design.
You are developing a component that requries parsing a lot of XML tags. You have abstracted the responsibility of finding the handler to a class named XMLElement Dictionary. Your will be invoking GetHandlerTag method of this class to find the corresponding handler method for a given element name (code snippet is shown below).
Typedef HRESULT(*PFNElementHandler)(IXMLAttribute* pAttributes, unsigned_int32nAttributes);
PFNElementHandler pfnElementHandler =( PFNElementHandler)
xmlElementDictionary.GetHandlerTag(elementName);
if(NULL!=pfnElementHandler)
{
(*pfnElementHandler)(pAttributes, nAttributes);
}
1. Define a datastructure that you will use inside this class to store the XML tags that you can use in your lookup logic for the fastest possible lookup on a given hardware. Call out your assumptions.
2. Implement the GetHandlerTag method.
A mail server exposes an interface as mentioned below. When given a day in the calendar a user, it gets the meetings mentioned as slots in calendar with start and end time for each meeting.
CalendarSlot *GetMeetings(char[] username, unsigned int day);
typedef struct
{
unsigned int StartTime;
unsigned int endTime;
}CalendarSlot
The developer has implemented a mail client function as mentioned below. This function takes in a list of users, internally uses the GetMeetings mail server interface to get the list of meetings for those users. Eventually, it gives out the first 10 free slots, within the next 3 days from the day specified, which is of the mentioned slotDuration. Everyone in the userList have to be free from meetings during these slots returned, without exception.
Assumptions:
1. Meeting start time and end times will align at the beginning of an hour (8:00,9:00etc....)
2. SlotDuration will be in multiple of full hours (1hrs, 2hrs,etc....)
CalendarSlot * GetFreeSlots (char [][] userList, unsigned int day, unsigned int slotDuration)
Write the test cases for testing GetFreeSlots function. NOTE: Assume that GetMeetings function is already well tested.
Given two arrays A & B of length l, containing non negative integers, such that the sum of integers in A is the same as sum of integers in B.( The numbers need not be the same in both the arrays.)
Now if you start with an index 'k' in each array and do the following summation, SUMMATION (Ak-Bk), where Ak is the value at index k of array A, and Bk is the value at index k of array B, where 'k' increments and wraps back all the way to k-1, the final sum value will be zero.
Question: Find a suitable 'k' such that during any point in the summation, SUMMATION(Ak-Bk) is always non negative. Find such a 'k' in O(n) time.
Print nodes at k distance from a given node like :
both upper side and lower side
A fair die is rolled, you will be given the amount in dollars, equals to the number that shows up on the die. Up to how much dollars you will pay for playing once?
Toughest project, One improvement to current Amazon website (may be related to usability or new feature), few object-oriented concepts.
Write a function to find out longest palindrome in a string.
I was also asked about one interesting system design (not Object Oriented) but I don't remember it properly (I was interviewed almost one month back)
Implement queue using stack/s.
Given a binary tree write a function to save it to file and also to reconstruct tree by reading from same file.
Given set of n points (Xi, Yi), write a function to find k nearest points from origin.
A bag contains 5 coins. Four of them are fair and one has heads on both sides. You randomly pulled one coin from the bag and tossed it 5 times, heads turned up all five times. What is the probability that you toss next time, heads turns up. (All this time you don't know you were tossing a fair coin or not).
How do you avoid dangling pointers and dangling references? Can you have a const reference to an object i.e. MyClass& const refToObj;? Does having a const* to an object guarantee safety from seg faults? What is the best alternative?
What is a dangling reference? Give sample code.
Why does the following code throw segmentation fault?
int main(){
int myArray[10] = { 1, 2 };
delete[] myArray;
}hw will u improve the 5s in ur shopfloor
Find the intersection of 2 unsorted arrays.
The interviewer asked me about the various methods possible and asked me to code one.
Verify if two BSTs are same, if same is defined as BSTs contain same sorted int array.
Find all numbers with same popcount number
Design a resource pool, which promises FIFO to every client
Find kth number in a BST
Given a N*N Matrix.
All rows are sorted, and all columns are sorted.
Find the Kth Largest element of the matrix.
You are given a array with rows sorted and column sorted. You have to print entire array in sorted order.
Write a query which return 5 persons who had spent most from a table and table contains customer id, product id and expenses. Customer id can be duplicate.
Write a code which return square of any number, but you can not use Star or carrot sign.
There is 3 text file, like 2008.txt, 2009.txt etc. Every file contains customer id, product id and expenses. Now write java code which will return 5 persons who spent most in these three files. Customer id can be duplicate all over files.
what is integration service with detailed
What happens when you get a segmentation fault? how do you get it and how is it implemented?
Given an array of integers, each element represents the max number of jumps can make forward. What is the minimum number of element selections to reach the end of the array (starting from the first element).
Example: arr = 1, 3, 5, 8, 9, 2, 6, 7, 6, 8, 9
Here the min # of selections is : 3
with the sequence : 1-> 3 -> 8 ->9
First element is 1, so can only go to 3.
Second element is 3, so can make at most 3 jumps: eg to 5 or 8 or 9.
If an element is 0, then cannot make any jumps
Print an arbitrary tree, level by level
Print out all the subsets of an array
Given P machines, each containing an array of N elements, find the medium of the array resulted by concatenating all the arrays on the machines.
You cannot move data across machines.
Question asked in microsoft written test :
Write a function which finds a substring in a string and replaces all such occurances with another string. Prototype of the function :
char* FindReplace(char* src, char* find, char* replace);
i'm looking for an algorithm writen in rcursion on java. building a board with x switches so that all the rest of the board is bulbs (say signed as @), each switch has a strength so it make all the bulbs around it change their stats (on-off or the opposite). for example:
@@@@***@@
@@@@*S*@@
@@@@***@@
* -meaning lights on
say switch in some coordinates and strength =1
the algorithm would find the maximum possibility of lights on, not all switches must be on.
1.Find is there a way on a grid from bottom left to top right. On the grid few tiles are blocked. Only right and up movement is allowed.
2.Find in how many min num of steps you can reach in above grid. Movement allowed is left, right, up, down.
3.Print the shortest path in above question.
There are 9 stones on the table, one is little heavier that other 8. Using a medical scales, how would you find the heavier one with exactly 2 measurements
3 friends are sitting at the table and they want to know their salary’s average, but without knowing each other's exact salaries. Develop a strategy for them.
You are given a binary tree with the following node structure:
struct Node
{
int data; // some data
struct Node *left, *right; // References to left and right children
struct Node *previous, *next; // References to previous and next nodes
};The tree is initialized with previous = next = NULL for all the nodes.
Using the previous and next pointers construct a doubly linked list such that each node's next is the node to its right at the same level and the last node's next is the first node at the next level.(similarly previous). The algorithm should have space complexity O(1). i.e., should be done without using extra data structures.You are given a binary tree with the following node structure
If you were writing a function in a calculator to compute sine/cosine/tangent, and all you had was basic math operations (+, -, *, /) how would you do it? You cannot use lookup tables.
I thought about a polynomial whose coefficients are integers and non-negative (its degree can be any non-negative integer and by definition, all exponents are non-negative integers). You can ask me exactly two question about value in any point you want. What is the polynomial?
you are given n files with m entries in each line separated.
for example file1 has a\n b\n c\n d(where \n is new line character)
similarly file2 has a1\n b1\n c1\n d1\n
and file3 has a2\n b2\n c2\n d2\n
your job is to print total 4^3 combinations.
Its not mere permutation problem.
the output is like
a a1 a2 \n
a a1 b2 \n
a a1 c2 \n
a a1 d2 \n
a b1 a2 \n and so on. i.e total combination of file2 and file3 with a
....
....
....
....
b a1 a2 \n
b a1 b2 \n
b a1 c2 \n
......and so on toal combination of file2 and file3 contents with b
......
....
similarily for c (16 lines)
and similarly for d (16 lines)
Hence total of 4^3 64 lines...
Note:- you have to do it by recursion.
there can be m files and n entries in each...
so don't hardcode for 3 files.How do you find the depth of the minimum depth node in a binary tree?
In the tree below the minimum depth is 3 (of node 22).
20
/ \
5 25
\ / \
7 22 30
/ \ \
6 8 33
\
35Suppose you have a large file with lots of words. How would you find the unique words and their count?
What kind of data structure u will use? What will be the time complexity and space complexity?
Suppose one string is "hello everyone" and another string is "everyone is good", then resultant string should return "hello everyone is good".. One "everyone" should be omitted in resultant string.
how to select random k elements from a linked list, when the size of linked list can not be determined
You have an integer array of length N, containing values in the range 1,2,3…N^2. Sort the array in O(N) time
What are synchronization primitives? How do you make sure to unlock a mutex which was locked in a thread that dies/terminates?
What is a futex?
What is a singleton class? Explain the code?
How do you handle singleton object in multithreaded programs?
Given an array containing lower case and upper case alphabets and numbers, how can you sort/arrange the array in one single pass using just one variable for swapping such that the resultant array should put the input elements into 3 buckets in the following fashion -
Input - aA1B23Cbc4
Output - abcABC1234
Note - ordering doesn't matter
the output could be -
ABC1234abc or 1234abcABC
You just have to arrange the data into 3 buckets in single pass using just one temp variable for swapping. Expected runtime - o(n)
Binary Search Trees, Deepest Common Ancestor, time complexity to insert best case and worst case..
Wht is Hastable and give time complexity to insert, lookup , wat is characteristic of good hash function..
Design a linked list.. Add nodes to both front and rear , also other operations possible with linked list... Display, Delete....Disadv of linked list
You have 100 coins, 29 of them are heads, rest are tails. You are BLINDFOLDED. You can reverse any coin. Your task is to divide this 100 coins into two groups in which there will be the same number of heads.
How do you find a binary tree is balanced or not. No two leafs in the tree has a level difference (distance from root) greater than one.
You are given a sorted array and it might contain duplicates eg arr=[ 1 2 2 3 3 5 6 7 8 8],two values say num1=4 and num2=8 Program should return the range of numbers from 4 to 8 .Can someone give me the code for this.
How to serialize strings and pass it over the network and de-serialize the string? The string may contain any possible character out of 256 valid characters.
The interviewer tried to give a hint "how do you escape characters in a string" !
Should the answer be use serializable in Java? Or is there a specific algorithm?
Find the most populous character in a string? Most optimal solution is desired.
Find 2 smallest numbers in an array?
Use of Static in C++.
We have a rectangle
It is divided in eight parts by three vertical and one horizontal line so that there are 8 chambers.
Now we have numbers from 1-8 to be filled in these chambers.
Rule : No two consecutive numbers must be present either side to side or diagonal
Invalid situation example
Given 5 at position 2 then 4 cannot occur at any of the give position.
4 5 4
_ _ _ _
4 4 4
_ _ _ _
One header file(a.h) includes another header file(b.h). Also, (b.h) header file includes (a.h) header file. What problems can occur because of this,if any?
Use of extern.
Use of static.
What is VLAN? How many bits are there in IPV4 protocol. What is RFC?
Difference between Router, Hub and a switch.
Which one is better? HashTable or Binary balanced trees? List scenarios when you will prefer HashTable.
You are given a series of XML file.How will you parse the XML and convert to a java object.
5) Programming question:
a. Given two integer arrays and the size of each array.
b. Determine if arrays match.
c. Order of elements does not matter.
d. Number of occurrences does matter.
e. Return true for match, false for no match
f. Computational complexity is important.
4) List sorting algorithms.
a. What is the Computational complexity of merge sort
3) In terms of practicality, describe a hash table.
2) List as many data structures as you can
1) Describe your most technical challenge in the last year.
If you have a 2 GB file with one string per line, which sorting algorithm would you use
to sort the file and why?
Given a pointer to the root node of a Binary tree, find whether the left subtree is an exact mirror of the right subtree.
give both recursive and iterative methods.
PS: If you fold the tree at the root note the left subtree should exactly fit in the right subtree
1.Desing a employee database for given conditions.
2.whats normal form. why use denormalization ?
3.Whats is index . How it is created . the internal of index which index to use when.
4. Deadlock quesitons
5. threads and process diffrence
6. virtual memory
1.Find faulty coin stack in 3 chances when u know u have 10 stacks of coin and one of them weighs less than the others.all others are of equal weight
2. Now u know that all of them 100 grams and the faulty one weighs 90 grams . find the faulty stack in 1 chance.
3. Out of 12 coins u know one is faulty can be more or less find the faulty coin in at most 3 chances.
1. Reverse a singly linked list
2. Insert node in a singly linked list arranged ascending order.
function to divide two number without using the divide operator
Given a number find whether the digits in the number can be used to form an equation with + and '='. That is if the number is 123, we can have a equation of 1+2=3. But even the number 17512 also forms the equation 12+5=17.
Write a program , given a number n, find all the prime numbers that exist from 1 to n.
Write a program to find a cycle in a linked list.
Write the different test cases. If a cycle is found , how do we fix it ??
Wat is the run-time of this algorithm
You have a matrix containing integers (no range provided). The matrix is randomly populated with integers. We need to devise an algorithm where by we find a row number which matches exactly with a column within the matrix. We need to return the row number and the column number for the match. The order of of the matching elements is the same. For example, If, i'th row matches with j'th column, and i'th row contains the elements - [1,4,5,6,3]. Then jth column would also contain the elements - [1,4,5,6,3]. Given an n x n matrix.
Suppose here are n processes in the system and each one needs k instances of a resources to complete. What would be the minimum number of resources that you should keep in the system to ensure no deadlock in the system.]
a.n*k
b.n*k-n+1
c.n*k+1
d.n*k*k
e.None of the above
Given an array of size n wherein elements keep on increasing monotically upto a certain location
after which they keep on decreasing monotically, then again keep on increasing, then decreasing
again and so on. Sort the array in place (ie. using only O(1) extra memory).
a function that removes the nth element from the end of a single linked list.
For example RemoveNthFromEnd ({1, 2, 3}, 1) should return {1, 2}
Also consider the case where the list has a cycle.
Node RemoveNthFromEnd (Node Head, int number)
{
}
Say, you have an nXn grids of alphabets. If you are at (i,j), you can concat with all character adjacent to you except yourself. For example, you have grids like:
abc
def
ghi
from (2,2), you can form substrings:
e, eb,ec,ed,ef,eg,eh,ei
ead,eadg,eadgh,eadghi,edghif,edghifc...
Note that the string never visit a character twice.
How many such substrings can be formed in an nXn grid? Can you write it in closed form?
Imagine you've a sorted list of strings and its encoded into another list, how do you determine the decoding scheme ?
write a function for ftoa..similar to itoa..
3) How would you find the phone number of an interview candidate if you don't have it on the resume?
2) How would you test a calculator?
phone interview
1) What are your goals?
best data structure to implement hash tables
Write the code to find the depth of a binary tree ( balanced and unbalanced) .
write the test cases to check the validity of the code.
trace the code for the test cases.
You are given a lot of cuboid boxes with different length, breadth and height. You need to find the maximum subset which can fit into each other.
For example:
If Box A has LBH as 7 8 9
If Box B has LBH as 5 6 8
If Box C has LBH as 5 8 7
If Box D has LBH as 4 4 4
then answer is A,B,D
A box can fit into another only and only if all dimensions of that is less than the bigger box. Also Rotation of boxes is not possible.
Imagine a goat placed at upper-left corner of a matrix A[i,j ]and the goat has to go to the lower-right corner of matrix . Now the goat can move only right or down such that when it moves to a different point it eats the grass at that point . If A[i,j] = Acres of grass at the point then write a code in C++ such that the goat eats maximum grass and also moves closer to its destination .
Design a class (OO) or DB for a Video library
Write code for Ceaser Cipher Algorithm to encrypt/decrypt messages.
Write an algorithm to convert string "1234.56" to its float equivalent.
Solution:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MSIntervewPreparation
{
class ConvertStringToFloat
{
static void Main(string[] args)
{
string str = "1234.56";
float num = 0.0F;
float multiplier = 0.1F;
bool isDecimalReached = false;
for (int i = 0; i < str.Length; i++)
{
if (str[i] == '.')
{
isDecimalReached = true;
continue;
}
if (!isDecimalReached)
{
num = (num * 10) + (str[i] - '0');
}
else
{
num += (str[i] - '0') * multiplier;
multiplier *= 0.1F;
}
}
Console.WriteLine("Input String: " + str);
Console.WriteLine("Float Number: {0} ", num);
}
}
}Write a function to convert "1234.56" into its float equivalent.
Solution:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MSIntervewPreparation
{
class ConvertStringToFloat
{
static void Main1(string[] args)
{
string str = "1234.56";
float num = 0.0F;
float multiplier = 0.1F;
bool isDecimalReached = false;
for (int i = 0; i < str.Length; i++)
{
if (str[i] == '.')
{
isDecimalReached = true;
continue;
}
if (!isDecimalReached)
{
num = (num * 10) + (str[i] - '0');
}
else
{
num += (str[i] - '0') * multiplier;
multiplier *= 0.1F;
}
}
Console.WriteLine("Input String: " + str);
Console.WriteLine("Float Number: {0} ", num);
}
}
}Write an Algorithm for Finding Siblings in a Binary Search Tree.
Two people are travelling through flight. Both have parachute and jump anywhere randomly i.e none of them knows who has jumped where.(Assume there's a big desert and they jump at any random location). Now, both of them have a single piece of paper on which they can write instructions before jumping and that's the only way they can meet each other. What would they write on paper before jumping ?
Given an analog clock, it's hour hand and minute hand divide the clock in two sectors. Write a function to return where the second hand is located ? in larger section or smaller?
Given time in format -
hh:mm:ss
Handle special cases carefully.
Write a program to reverse a string. Two cases -
1. When length of string is known.
2. When length of string is unknown.
Come up with as many test cases as you can.
Given two sorted singly linked lists L1 and L2. Make L1 like L2 i.e say,
L1 = 10->30->45->80->null
L2 = 2->22->35->56->100->null
Then after writing the program, L1 should look same as L2
Write a program to remove duplicate elements from array.(Array contains elements in range 1...N). Algorithm must be O(N) in time and O(1) in space. Come up with as many test cases as you can.
Write a program to find intersection of two rectangles. Come up with as many test cases as you can.
Given a Binary Matrix of 0's and 1's.
Write an algorithm to:
1) Print the largest Rectangular Sub-matrix with all 1's.
2)Print the largest Sub-matrix with all boundary elements 0.
Explain your whole algorithm with an example.
Explain Inheritance
Write algorithm to count no of words in a file. What kind of words would you filter? (e.g. TAB etc)
Design class PhoneBook. He was interested in data structure and prototypes of different methods.
Find longest interval:-
We are given with two arrays A and B..each of size
N...elements of array contains either 1 or 0...
we have to find such an interval (p,q)(inclusive) such that the sum of
all
the elements of A (between this interval) and sum of all elements of
B
(between this interval ) is equal...
i.e.
a[p]+a[p+1]....+a[q]= b[p]+b[p+1]....+b[q]
find max sum of a matrix
write a perogram where an array of integers, e.g.{10203004567000} is given, you have to create a new array which will be like (12345670000000}, without using any other temporary array.
Given three lists: A, B and C of length n each. Write a function which returns true if any 3 three numbers (1 from each list), sum up to zero. Else return false, if there is no such combination.
you are given a M x N matrix with 0's and 1's
find the matrix with largest number of 1,
1. find the largest square matrix with 1's
2. Find the largest rectangular matrix with 1's
There is an ant which can walk around on a planar grid. The ant can move one space at a time left, right, up or down. That is, from (x, y) the ant can go to (x+1, y), (x-1, y), (x, y+1), and (x, y-1). Points where the sum of the digits of the x coordinate plus the sum of the digits of the y coordinate are greater than 25 are inaccessible to the ant. For example, the point (59, 79) is inaccessible because 5 + 9 + 7 + 9 = 30, which is greater than 25. How many points can the ant access if it starts at (1000, 1000), including (1000, 1000) itself?
Program sum of 1 to 10 numbers.
explain your answer
If you used arithmetic progrssion fot answer then derive the answer without mathematical proof/induction/using example for your answer (you should not be calculating 111111111 numbers as an example for instance)
Given an integer array of which both first half and second half are sorted. Write a function to merge the two parts to create one single sorted array in place [do not use any extra space].
e.g. If input array is [1,3,6,8,-5,-2,3,8] It should be converted to: [-5,-2,1,3,3,6,8,8]
what is the output of
for(;0;)
printf("\n guess");
and why?
Convert String = "98989" into an integer without using any library functions in java.
Give fastest way to do it and explain why your method is best.
Write automation design for testing ping.exe. Write classes you need to support validation of inputs and return values. Show what specific input values and return values you would use to validate it.
C:\>ping.exe /?
Usage: ping [-t] [-a] [-n count] [-l size] [-f] [-i TTL] [-v TOS]
[-r count] [-s count] [[-j host-list] | [-k host-list]]
[-w timeout] [-R] [-S srcaddr] [-4] [-6] target_name
Lets assume we have a rat maze as represented by the following NxM matrix
where S is the start location and F is the end location.
S 0 0 0 0 0
1 1 0 0 0 0
1 0 1 0 0 0
1 0 1 0 0 0
0 1 0 1 0 0
1 0 0 0 1 0
0 1 1 1 1 F
The idea (as with any rat maze) is to traverse from S to F. The matrix can
have only 0 and 1 as values. 1 represents a path that can be taken and 0
represents a blocked path.
We can make the following assumption:
S will always be (0,0) and F will always be (N,M).
As seen from above, there can be many paths from S to F.
How do we find the shortest (or longest) path from S to F without actually
traversing all the possible paths.
Please post (with proof/explantion) your algorithms. Also can you then think
of ways to optimize the algo?
Write a "C" function,
int AddOvf(int* result, int a, int b)
If there is no overflow, the function places the reusltant
sum a+b in "result" and returns 0. Otherwise it returns -1.
The solution of casting to long and adding to find detecting the
overflow is not allowed :-)
You are given a mathematical expression containing operans , operators and parantheness.
Test weather it is a valid expression or not.
You are given a sorted array such that all the number is repeated except one.
Find that non repeated number in O(n)
You are given an array of positive integers.
Find a subarray such that the (length of subarray)* mininum value in that subarray is maximum.
You are given an array of integers.
Find the mininum value of all the subarrays of size k in O(n)
Given an input sequence of characters like abcd... . Write a function which tells if the input received so far is palindrome. is it possible to tell without storing all the input sequence?
something like an infinite stream of characters.
an array contain +ve and -ve element, find subarray whose sum =0;
Explain the memory alignment for advancing an short array pointer cast to a void
How to find duplicate words in a string and their frequency
implement the double trouble game in Java
In a nxn board, some nodes are black colored. Given a black node, highlight all the black node connected to this given node directly or indirectly.
Implement a circular queue using an array. Implement enque and deque.
Given
class Node
{
string A,
NodeList children;
}
class NodeList
{
int count;
Node GetAt(int index);
void AddNode(Node node);
}
Implement deep copying a Node.
How will you delete duplicate odd numbers from a linked list? (delete only duplicates, keep one copy, list is not sorted) Interviewer was expecting O(n) answer. He didn't say anything clear about the extra space.
Implement the following Interface with a Tree implementation of a Map.
public interface Map<K extends Comparable, V> {
public void put(K key, V value);
public V get(K key);
public int size();
}
2,2,4,11,_
Find the next number in the series.No more clues.
[I had 1 hour and gave many possible answers like 50,28,67 and 18 but could not convince them. This is such a short series.]
You have an Array of a million numbers. Duplicates exist in the array.
Print out all duplicate numbers.
Give best way to do this.
Xbox for Zombies:
There are 10 zombies wating for the new Xbox in a line at a store. The store has 4 lanes, i.e. 3 waiting lanes and 1 purchase lane. The zombies are standing in the first waiting lane (ordered 1st to 10th)
All zombies have to end up in purchase lane in the same order, you can use the other waiting lanes and can move only one zombie at a time. You can talk to and move only the front zombie in any lane if you talk to any other zombie behind the first one then it will eat you. Ex: if zombies 3,6,7 are in lane 2 then you have to move zombie 3 to other lane if you want to move zombie 6.
Also, if the i'th zombie sees any zombie greater than i in the same lane then it will kill all zombies. Ex: if zombie 4 sees zombie 5 or greater in front of it in the same lane then all zombies will be killed.
And you can only move zombie's from the front of the lane, the back of the lanes are closed. So if you move zombie3 to purchase lane then only zombies 1&2 can be moved to that lane because any other zombie greater than 3 cannot stand in front of zombie3.
Think of the lanes as a stack.
In how many moves can you move all zombies into purchase lane without killing yourself and any zombies?
Give several examples that static class function is useful.
Find the width of a tree pointed by head
description of a class that you designed.
operator++, op<<, copy ctor, assignment syntax,
name 3 process synchronization methods.
which is tightily coupled containment or inheritance
How would you design http://www.google.com from the ground up?
A Binary Tree is represented in an int array such that if P is parent and c is its children..a[c]=p
a) Construct a Binary Tree if Such An Array is given…
b) u’ve given an index of node representing root of sub tree.. If we ignore the node and all of its descendants , tell the no.of nodes remaining in tree….
Given two strings, find the number of occurrences of one within the other . eg s1=" the cow ran over the dog" s2="the" answer =2. Also, take care of repetitions eg. if s1= "ABCBCBC" and s2="BCBC" then answer=2
Given a n array of positive and negative integers, find the subarray with max sum in O(n) and one loop.
How do you test function Add that adds two linked lists?
Find the frequency of each letter in a string. then test it.
Given a chocolate bar of size MxN and a list of pieces, determine if the chocolate can be divided into the specified pieces. Example: Given a chocolate bar of size 3x4, determine if it can be divided into pieces of sizes (areas) 1, 2, 3, and 6. (In this case the answer is 'true'.)
Detect a cycle in a graph
What is the probability of a random generator generating 10 consecutive numbers in ascending order (assume it is a perfect random generator)
write a function to evaluate following expression
5+4-3*2
Given a denomination and an integer find out in how many ways can the number integer be written via denominations
int function (int [] ,int N){
}
int denomination[] = [1,2,5,10]
N=6
1+1+1+1+1+1
1+1+1+1+2
1+1+2+2
1+5
2+2+2
answer 6
given a link list of form
A1-A2-A3----An-B1-B2-B3---Bn
convert it to following
A1-B1-A2-B2-A3-B3---An-Bn
struct A
{
char c;
int i;
};
what is the size of structure? and why? And how to make compiler to allocate exact 5 bytes to the structure object?
Implement a data structure similar to stack which supports Push, Pop and GetMin in O(1)
Compare pangrams with string and find missing letters.
Provide animation of particles in string format.
BST depth of tree intuition.
The plane problem with 100 passenders one losing ticket. Probability of last guy sitting in right spot.
If there are 3 dots on a circle, whats the probability of 2 of them lying on the same side.
How would you choose m random numbers between 1-n.
how would you find the missing numbers in 1-1M with least possible space complexity.
write code to reverse xyz___pqr___abc into
zyxrqpcba. Give the most optimal solution.
How do you describe a printer to your Grandma?
How do you describe pointers to your Grandma?
Implement aligned memory allocation using the standard malloc function
How do you implement a Mutex
What does the Static key word used in C qualify?
How do you make objects respond to events.
Your most proud achievements.
design a class for bakery. Open ended problem, trick is to be consistent.
Write a program to find sqrt of x.
Can return type of an overloaded function be different. C++
const char *myfunc()
{
string str("return this");
return str.c_str();
}
Write strcpy(char* src,char*dst). Given src points to a NULL terminated string.
What is the output of the following?
unsigned short us = 6;
unsigned short us1 = 7;
unsigned short us3 = 8;
printf(?%d\n?, us & 0x00 );
printf(?%d\n?, us | 0xFF );
printf(?%x\n?, ( us & us1 ) | us3 );
printf(?%d\n?, ( ( us << 2 ) & us1 ) | us3 );*/
Given bucket of jelly beans 16 red, 32 blue, 48 yellow. How many do you have to pick to have two of same color?
Reverse a 4 digit number in one statement. Ex: int n =1234; x= <your code>; cout<<x; //Output: 4321
Describe the singleton pattern - its purpose and implementation.
What things should you take into account when you are planning to use multiple threads in your program. And the one connected to this was: What is deadlock and how do you prevent it?
Explain what is Overloading and overriding.
What is polymorphism? Give an example.
What is STL auto_ptr? How do you use it and what problems should you be aware of when using it.
Describe smart pointer and how would you implement it.
A robot has to move in a grid which is in the form of a matrix. The robot can go 1) A(i,j) to A(i,j+1) or 2) A(i,j) to A(i+1,j). Find an efficient way of computing the unique number of paths from A(0,0) to A(m-1,n-1) for the grid represented by the matrix A mxn
Given an array of n numbers (A1, A2, A3....An)(where Ai can be positive or negative, i=1 to n), find the value of maximum sum of all sub-array's sums, such that these numbers (in the sub-array) are continious in the given sample.
Example:
-1,1,3,-1
The max value for the sub-array is 4. The continious sub-array is 1,3
If the input was 1,-1,-1,3
then our answer is 3 since 1 and 3 are not continious
give an example of symbol table, semantic stack and parse table in an compiler implementation
How is C++ related encapsulation, inheritance and recursion
Given the following searching algorithm, what is the complexity and how would you improve it.
If you have a file with 1 trillion numbers, but memory can hold only 1 million, how would you find the lowest 1 million out of all these 1 trillion numbers?
Implement a stack that can have push, pop and find_minimum operations in o(1) time.
Write code for Huffman encoding.
how to find that a given string is palindrome given a string can contain space as well. we don;t need to consider space. eg: a cd ef ed ca is a palindrome.. try to reduce to more efficient alogorithm
Compute square-root of a number x. what's the stopping criteria? What's the time complexity?
Given an undirected graph, find if it is bipartite or not. Return true or false.
Telephone Dir lookup:
Given mapping: number to letters (just like on the telephone buttons)
i/p: digit string e.g. "1234"
1. o/p: all possible letter strings based on the mapping.
2. o/p only those strings that are in a given dictionary. (and length of the dictionary is small.)
Imagine you are running a typical dropbox website (like x-drive) where users can upload their files/data. How will you go about monetizing this website using online advertising? What are the factors you will consider to match users to ads?
Given a histogram of n items stacked next to each other, find the Max area under a given rectangle.
Each bar in the histogram has width = 1 unit and hight is variable.
Hint: Brute force approach gives you O(n2) solution. Can you do better?
Find and delete nodes from a linked list with value=k. What's the complexity? Does it handle boundary cases?
Hint: Make sure to free the memory when deleting a node using delete() or free()
Implement Queue using stacks. What's the time complexity of various queue operations for this implementation?
Find 2 numbers in an integer array that sum to x. If found return true else false.
1. simple solution is O(n2)
2. Using certain data struct it can be improved to O(n) but you have to check for a special condition. what is that? Hint: if x = 4 and one of the values in the array is 2.
"Count and Say problem" Write a code to do following:
n String to print
0 1
1 1 1
2 2 1
3 1 2 1 1
...
Base case: n = 0 print "1"
for n = 1, look at previous string and write number of times a digit is seen and the digit itself. In this case, digit 1 is seen 1 time in a row... so print "1 1"
for n = 2, digit 1 is seen two times in a row, so print "2 1"
for n = 3, digit 2 is seen 1 time and then digit 1 is seen 1 so print "1 2 1 1"
for n = 4 you will print "1 1 1 2 2 1"
Consider the numbers as integers for simplicity. e.g. if previous string is "10 1" then the next will be "1 10 1 1" and the next one will be "1 1 1 10 2 1"
Given a binary tree, compute min depth of a leaf node.
Hint:
1. BFS
2. Recursive implementation
Which is better in time complexity?
1. Compare and contrast Arraylist and Linked list based on time complexity of various operations.
2. Inserting into Arraylist and it's complexity. Consider dynamic memory allocation in order to expand the list.
Tower of Hanoi and it's time complexity for tower with n disks.
Given a sorted integer array (e.g. 1 2 3 4 5). It is shifted by k pos to right (e.g. for k=2 and the new array is (4 5 1 2 3). Find what's the value of k based on the new array.
Hint: O(n) solutions is obvious. Can you do better? say O(lg n).
Implement count Non-leaf nodes on a binary tree.
In an XY plane, find number of path from origin(0,0) to any point (x,y) subject to following conditions:
1. x,y are +ve integers
2. From a position you can move either right or up.
int numPaths(x,y)
(Hint: It can be solved by dynamic programming)
Find if 2 numbers add up to some number x in an array of integers.
What's the difference between Bandwidth and Latency?
1. When do deallocks occur?
2. How to avoid them?
1. Types of DB intexes
2. what is index fragmentation
Implement int countNode(Node* n) on a binary tree.
1. Implement ReverseLinkedList(Node* n).
A and B have 1 hour window in which they can meet. Whoever comes first will wait for the other for next 10 minutes and then leave. what's the probability of them meeting?
Given points (x1, y1) and (x2, y2) defining a line in XY plane, write functions bool isAboveLine(float x, float y) which returns true if the point (x,y) is above the give line or false if not.
Implement recursive shuffle(int[] A, int n).
Implement queue using stacks.
1. Implement linked-list
2. Use above to implement queue. Give time complexity of enqueue(), dequeue(), search(k)
3. Improve search(k) complexity to O(1) by modifying the above data stuuct( Hint: Linked Hashmaps)
You have to transform a given word to another word with minimum number of changes, changing only one letter at a time. All the intermediate words should be a dictionary word.
Ex. fox->cog= fox->fog->cog.. answer is 2
Given a binary tree, and 3 nodes x,y,z write a function which returns true if y lies in the path between x and z and false otherwise.
Given an array of length N. How will you find the minimum length
contiguous sub - array of whose sum is S and whose product is P . Here
S and P will be given to you.
was asked in YAHOO CODING ROUND interview
Return the nodes only a particular level of the BST.
given: level, from which nodes to be returned.
Write a program to display all the anagrams for "abcdef". Which language would you do it in and why? Which is the best language to use for coding this?
Implement a search engine. The input will be 100 text files. Return the paragraph and the file in which the keyword appears.
Implement a phone directory
Implement Twitter's trending topic.
The input is a text file. Implement it in C.
1. what is virtual memory
2. Difference between process and thread
3. Design a game with 2 players who have health as a parameter.
Given post order traversal of a BST, construct the BST. Also specify the time and space complexity
Delete n'th element from the end of the singly linked list
1. Find the largest subtree in the given binary tree which is a BST. (Subtree can refer to any part of the tree.Only root node and its children are also a subtree).
2. Reverse the given linked list for k elements.
Eg. when k =2 for list 1->2->3->4, reversed list should be 2->1->4->3
1. how to find the no.of times a number has repeated in a sorted array?
2. Given two binary trees, merge it into a single binary tree
find one missing card from deck of 51 card
Convert a max heap to min heap.
given string
input1, input2, remove wherever the occurence of input2 in input1.
e.g:
input1: abcthabdtheshhtexyztheaaa
input2: the
will become abcthabdshhtexyzaaa
give the test cases.
Output ?
int i = 0 , a[3] ;
a[i] = ++i;
printf (" %d %d ",a[i],i) ;
Given two lists. Write a function to check whether both the lists are equivalent or not.
(Two lists are said two be equivalent if both of them contain same elements with same frequencies in both the lists).
Convert a doubly linked list to BST in place
After writing the code I was asked to turn over the paper and create/draw ten test cases to test my program.
Write a function that takes in two rectangles and returns true if the overlap and false if they do not.
Write code to find the power set of a given set. for example if S={a,b} the power set is P={{},{a},{b},{a,b}}
Write code in C,C++ or java to find whether a given binary tree is mirror image of itself??
This is my biggest doubt, i feel people keep different ideas. The question is:
Does constructor return anything? Yes/No. Justify.
Any person who has really done some research on that, let me know it. Some technical people think..YES(returns object of same type). some say NO......I feel NO and I have done some research. Please help me.
Find kth smallest element from an unsorted array in linear time. worst case complexity should be O(n+k)
where n is array size.
Given an unsorted array provide two indices n1 and n2 such that if we only sort the elements between n1 and n2,then the whole array will become sorted.
n1-n2 should be as minimum as possible.
Delete duplicates from a sorted array in O(log n) time and O(1) space.
Write an O(n) algo for finding two elemnts in an unsorted array which sum to a given element x.
I told hashing.Then he told me to do without it because space complexity becomes high in case of hashing.
I took around 30 minutes and was not able to find any other O(n) solution :(
Explain me how would you solve the 8 queens problem .
(Thank god he did not ask for the code)
Reverse a singly linked list under following restrictions.
1) Cannot use additional n memory to create temporary list.
2) List is immutable.
Write an efficient recursive function for finding Fibonacci series .
(Use backtracking to avoid finding the terms which are already been calculated).
Suppose i am using quick sort to sort an array using its middle element as pivot
i.e. pivot=low+(high-low)/2.
Explain with example the case when it will become O(n^2) instead of O(n log n).
How to do conditional compilation of a c program in unix
Convert a min heap to BST without changing its structure and of course no extra space .
Convert a BST to max heap without using extra memory and in as optimum time as possible
What are NP-complete and NP-hard problems
explain with examples
I was explaining the solution of a question by using hash table.
Then he grilled me on that
What is a hash table ......
Design your own hash table and write code for it
Provide test cases
From here the disaster started :(
So be careful before uttering any term, u should have enough confidence on that.
Explain how to find the time complexity of a recursive function .....
Derive time complexity of recursive postorder binary tree traversal .......
I was screwed up by the derivation :'(
Find all permutations of a string.
I gave the following function .
public static ArrayList<String> perm(String s)
{
if(s==null)
return null;
if(s.length()<=1)
{
ArrayList<String> a=new ArrayList<String>();
a.add(s);
return a;
}
char c=s.charAt(0);
ArrayList<String> a2=perm(s.substring(1,s.length()));
for(String s2:a2)
{
for(int i=0;i<s2.length()+1;i++)
{
String s3=insert(s2,i,c);
a.add(s3);
}
}
return a;
}
public static String insert(String s,int i,char c)
{
String s1=s.substring(0,i);
String s2=s.substring(i);
String s3=s1+c+s2;
return s3;
}
Then he asked me to find its time and space complexity in terms of n where n is the length of input string and also asked me to give test cases.
What's the problem with this code ?
class A
{
public :
int x,y;
A(int i=0,int j=3):x(i),y(j) { }
};
int main()
{
A a();
cout<<a.x<<a.y;
}
given eight 8s: 8 8 8 8 8 8 8 8, add any number of "+"s between the 8's to make the sum equals 1000.
given 5/2=3, what will be the output of 10/3?
two sorted arrays e.g. A[1,3,5,7,9], B[2,4,8,10,11,15, null, null, null, null, null], merge A into B and get a sorted B as output.
int[] doAction(int[] a, int[] b){
}
input a binary tree, check if this is a binary search tree
bool isBinarySearchTree(Node * root){
}
You have a set of points across the globe as longitudes and latitudes. How would you find all the points that are within n miles?
how to read a pdf,doc... file in c o java
Given a string having 2n charecters as c1 c3 c5 c7...c2n-1 c2 c4 c6 .....c2n
write an algorithm to rearrange the charecters so that the string will become as
c1 c2 c3 c4 c5 ......c2n
Max complexity of algo should be O(n)
Do it without using extra storage
given N jobs each require time T1,T2,.....TN times to complete,and their deadlines are D1,D2,D3,......DN.if they completed with in their dealines we get profits P1,P2,P3.....PN
here objective is to profit maximization.jobs are in orbitarary order.they are not sorted in any way.
49 race cars and no two have the same speed. Now give you 7 tracks with equal length to find the 25th fastest car. At least how many races are needed.(no time recorder)
Given a triangle you need to divide it in 7 equal non overlapping triangles
Following is a tree
A
/ \
B C
/ \ / \
D E F G
/\ /
H I J
You need to print
A CB DEFG JIH
Modified LEVEL order traversal
A set contains 1 million Points.
Given a Point(x,y) you need to find out 100 closest points.
A certain string-processing language allows a programmer to break a string into two pieces. Because this operation copies the string, it costs n time units to break a string of n characters into two pieces. Suppose a programmer wants to break a string into many pieces. The order in which the breaks occur can affect the total amount of time used. For example, suppose that the programmer wants to break a 20-character string after characters 2, 8, and 10 (numbering the characters in ascending order from the left-hand end, starting from 1). If she programs the breaks to occur in left-to-right order, then the first break costs 20 time units, the second break costs 18 time units and the third break costs 12 time units, totaling 50 time units. If she programs the breaks to occur in right-to-left order, however, then the first break costs 20 time units, the second break costs 10 time units, and the third break costs 8 time units, totaling 38 time units. In yet another order, she could break first at 8 (costing 20), then break the left piece at 2 (costing 8), and finally the right piece at 10 (costing 12), for a total cost of 40. Design an algorithm that, given the numbers of characters after which to break, determines a least-cost way to sequence those breaks. More formally, given a string S with n characters and an array L[1..m] containing the break points, compute the lowest cost for a sequence of breaks, along with a sequence of breaks that achieves this cost. (Dynamic Programming solution)
You are given a singly link-list such that each node of this list is also a
head of another link list of the same type. So, how does one flatten the
linked-list
struct node {
void *data; /* could be anything */
struct node *next;
struct node *down;
};
There are n princesses, there is one lamp inside a tower. A princess is picked randomly with repetitions and she can turn on or off the lamp. The princesses are picked infinitely. The princesses have to come up with a strategy to count the number of princesses by using the lamp information. (here lamp is a single bit, it can be on or off).
Given two arrays say
a={2,3,4....} b={4,7,1...}
Find k least sum where sum= single element of a + single element of b
Example if i say 2 least sum then
(least of a + least of b) and so on
More of a discussion and knowledge based question:
How would you determine which web pages are relevant to a place (think country-level)?
Given:
A regular 8x8 chessboard
One chess piece, a knight. Knights can move in an L-shape; two moves in either horizontal or vertical direction and one in the other direction.
Difference from a normal chessboard is that the knight is allowed to make a move that takes it off the board. But once it's off the board, it cannot move anymore.
n = The maximum number of moves that the knight is allowed to make
Find:
The probability that after n moves, the knight is still on the board.
Additional question after a solution was given:
How would you test this function that you've written?
This was only technical question my interviewer was asking to every candidate he interviewed
What kind of questions u will ask to me if u have to design a Queue for me ?
i answered as
1) for data type u want it
he said int
2) It is going to contain very large numbers of objects
he said no
3)do u want to dynamically expanding
he said no , lets keep it simple
4)do want functionality of accessing any element in queue like At() function
interviewer : yes
5)Do u want min and max element functions
interviewer : yes
After this he kept saying what else what else and i was blank
he mentioned asking about environment would have been a good question like do want this queue for kernel for application or for Database
then he asked me to write a class which will implement this but he was rushing a lot kept saying we have very less time left so i end up writing queue full , queue empty , insert and pop conditions only
i must say i was bit disappointed by this interview as from CareerCup i have prepared for alot of coding question and from these kind of questions will everybody answer easily , how will they screen candidates
what area u will like to improve urself when u r at work ? (i kind of interpreted it as if he is asking what is ur weakness and how will u improve )
Tell me any product in tech u dont like ? and y
What technologies u know ? rate ur self on those
What kind of products/project at MS u would like to work on and why?
Where do u see urself in MS after 3 years ?
So what improvement will you do to system u worked at internship ?
Hi i interviewed today for MS on campus. Most of the questions were behaviral and only one technical question . It was half hr interview and my interviewer was rushing through interview quite a lot . I really have no idea how they are going to screen candidates just based on this
Tell me what you are doing now a days
i explained my work done at intern .
maximum binary search tree (in terms of number of nodes)that can be in a binary tree
So the Problem being this.
Given a particular number say 637-8687 (NERVOUS) would be the word.
So for the older keypad’s seen on telephone’s I would have to create Mnemonics.
So for doing this, the first part being list out all the Permutations possible for a particular number series.
Ex: ListMnemonics(“723″) would result in
PAD PBD PCD QAD QBD QCD RAD RBD RCD SAD SBD SCD
PAE PBE PCE QAE QBE QCE RAE RBE RCE SAE SBE SCE
PAF PBF PCF QAF QBF QCF RAF RBF RCF SAF SBF SCF
For this my logic is
for the above number 723, somehow create all the permutations for 23 and then append for each of those permutations the letters of 7. That would give all the permutations possible for 723. The base case being if there is a single number then I would print its letters.
But please let me know what you guys think
Find first repeated substring in a given input string.
1. The repeated strings can overlap.
2. The repeated string should not overlap.
Write code for finding square root of a given no.
Given a matrix with each row and column sorted in ascending order. Find the median in the matrix
Given an array sequence, lets create a binary search tree taking one element at a time (sequentially from the array), and inserting it at the correct position in BST (without caring for balancing).
Consider the sequence: 2,1,3 --> resulting tree will be 2 as root, 1 and 3 as left and right child respectively.
Similarly, consider 2,3,1 --> again the same tree.
Question is: Given any such array sequence, find out the number of ways you can arrange this array which will result in the formation of exactly similar BST. (the answer for above example is thus 2: 2,1,3 or 2,3,1).
write code to reverse a string
give the recursive version
and why would anyone want to use the recursive version and when .?
write a program/function that converts a decimal number to its Roman numeral representation and vice versa.
What is a deadlock?
How can you avoid it?
What are the main concepts in multi threading code?
Level order traversal of a binary tree.
You are given a file containing integers in the range (1 to 1 million). There are some duplicates and hence some numbers are missing
Find the fastest way of finding missing numbers?
write a function to transform a MxN matrix (which can store 1,0) based on the condition
if( A[i][j] == 1) /* in input matrix */
the transformed matrix must have a[i][0...N-1]=1, and a[0 to M-1] [j] = 1. need lease space and time complx.
print Binary search tree by it's vertical order.find the space and time compl
Swap two numbers without using temporary variable. I dont know why he asked this simple question.
A character array contains "I am from Chicago". There is one byte of memory which can be used as temporary variable. Now reverse the words to get "Chicago from am I". How would you do that? Is there any better data structure that can be used instead of array to do this?
you are given n ropes,maybe of different length.
the cost of tying two ropes is the sum of their lengths.Find a way to tie these ropes together so that the cost is minimum.
Implement three stacks in single array
Implement two stacks in a single array. Please note that you should not report stack full until all the elements are full.
You are given a doubly link list and out of some nodes of this doubly linked list, some other doubly link list emerge and from some of these emerging doubly linked list, more doubly link list emerge. You have to write a quick algo that merges all these doubly linked list into a singly linked list
double i;
main()
{
(int)(float)(char) i1;
i1 i;
printf("\n%d",sizeof(i));
}
This returns 8. How?
make a LL from bst in spiral
nth largest element in bst
write acode for spiral m*n matrix
Given an array (can have negative numbers), find the sub-array with maximum sum. Follow-up question. Find the sub-array with minimum sum.
Given an integer array. Find the five most frequent numbers.
Given two strings s1 and s2. Write the program to delete all the characters of s2 from s1.
Design an algorithm to find all the anagrams in a dictionary and code it. Write the test cases also.
List the ways you can find the phone number of a candidate whose number is not working at the time of interview and as a interviewer i want to look for his number.
Reverse words in a string
I was asked to implement the something like 4*5+9
there can only be integers and only + - * and / operand
Given an array and a sum value return any two integers that sum upto the sum value. I gave a O(nlogn) solution I dont know if it is the best solution available.
Write a code to find if two linked list intersect.
I told two ways one by counting the length of the two linked list and then advancing the the bigger linked list by the difference in length and then advancing both the pointers simulataneously to check if they intersect.
Also i told a method to join the last node of a linked list to the first node and checking if a cycle exist.
Given 2 equal-length arrays of integers, find pairs, one from each array, that sum to 0.
-- note that one wrinkle of this problem over the more usual form, which is to do this in a single array, is that you can't use the indexes / iterators crossing each other to know to stop, rather their /values/ have to cross (if you're doing it right, at or near 0).
What's an efficient way to process a large file, with lines of varying length?
-- I said, break it up and process the pieces in parallel, using fseek to divide up the file, and scan backward and forward for the line terminators to decide which chunk a line belongs to. I think the answer he wanted though was to memory map it.
You have a fair coin. Make it unfair with win and loose probability p and (1-p) respectively, where p is greater than 0 less than 1
If a number is power of 2
use vs require keyword. How to create module
Lots of questions from previous experience. 80% of interview revolved around my past experience. One lady asked me three most challenging technical issues. I answered one in depth, she interrupted in between to move on to next one, but i didn't complete that answer yet. After I completed the answer, she moved on to next question!
Overall I prepared hell lot of questions and answers from embedded system, C and Linux. only a couple of simple questions asked. No linked list, data structure related questions from C, opposed to many feedback in careercup and in other sites. Most questions were around my past experience, some basic embedded questions and bit manipulations. I was disappointed as all preparation went in vain - especially a simple matrix question i was asked, wasn't able to answer correctly, which was a disaster after I knew the answer. Some interviewers probably were taking interview for first time. One kept checking emails while I was answering questions and somebody kept knocking the door (for fun) all throughout the interview. He told me just ignore that :) . The interview was for general positions, 'anything that's matches my credential'. I am supposed to get an answer in 1 week, it's been two weeks I haven't heard back. I think the matrix question from the director ruined my chance. But there were 7 interviewers. One told me and I realized in the beginning it wasn't a match in his group. But the other 5 went pretty well, as far as I think. Any one here got a reply back from Qualcomm after 2 weeks?
The director have me a matrix on paper and asked to generate the matrix. Very simple, once found out the answer - 5x5 from number 1-25, only diagonals were changed. Couldn't answer the question, probably that cost the interview. He asked another question to build a matrix from 1 to 100 without repeating any number. I told him to use recursion, he didn't agree.
In a file containing user address and other info find the one with a particular address location
Swap variables without using temp
Overall I prepared hell lot of questions and answers from embedded system, C and Linux. only a couple of simple questions asked. No linked list, data structure related questions from C, opposed to many feedback in careercup and in other sites. Most questions were around my past experience, some basic embedded questions and bit manipulations. I was disappointed as all preparation went in vain - especially a simple matrix question i was asked, wasn't able to answer correctly, which was a disaster after I knew the answer. Some interviewers probably were taking interview for first time. One kept checking emails while I was answering questions and somebody kept knocking the door (for fun) all throughout the interview. He told me just ignore that :) . The interview was for general positions, 'anything that's matches my credential'. I am supposed to get an answer in 1 week, it's been two weeks I haven't heard back. I think the matrix question from the director ruined my chance. But there were 7 interviewers. One told me and I realized in the beginning it wasn't a match in his group. But the other 5 went pretty well, as far as I think. Any one here got a reply back from Qualcomm after 2 weeks?
use vs require keyword. How to create module
The director have me a matrix on paper and asked to generate the matrix. Very simple, once found out the answer - 5x5 from number 1-25, only diagonals were changed. Couldn't answer the question, probably that cost the interview. He asked another question to build a matrix from 1 to 100 without repeating any number. I told him to use recursion, he didn't agree.
In a file containing user address and other info find the one with a particular address location
If a number is power of 2
Swap variables without using temp
Overall I prepared hell lot of questions and answers from embedded system, C and Linux. only a couple of simple questions asked. No linked list, data structure related questions from C, opposed to many feedback in careercup and in other sites. Most questions were around my past experience, some basic embedded questions and bit manipulations. I was disappointed as all preparation went in vain - especially a simple matrix question i was asked, wasn't able to answer correctly, which was a disaster after I knew the answer. Some interviewers probably were taking interview for first time. One kept checking emails while I was answering questions and somebody kept knocking the door (for fun) all throughout the interview. He told me just ignore that :) . The interview was for general positions, 'anything that's matches my credential'. I am supposed to get an answer in 1 week, it's been two weeks I haven't heard back. I think the matrix question from the director ruined my chance. But there were 7 interviewers. One told me and I realized in the beginning it wasn't a match in his group. But the other 5 went pretty well, as far as I think. Any one here got a reply back from Qualcomm after 2 weeks?
Automation experience. Seems they have 99% test cases automated.
use vs require keyword. How to create module
Lots of questions from previous experience. 80% of interview revolved around my past experience. One lady asked me three most challenging technical issues. I answered one in depth, she interrupted in between to move on to next one, but i didn't complete that answer yet. After I completed the answer, she moved on to next question!
Performance testing of a mobile phone.
Lots of questions on Linux kernel, interrupts and performance measuring of a multimedia application during lunch interview. Need to have basic knowledge on interrupts, kernel mode operations, memory management (e.g. how to detect memory leak - i answered dalloc or mtrace).
The director have me a matrix on paper and asked to generate the matrix. Very simple, once found out the answer - 5x5 from number 1-25, only diagonals were changed. Couldn't answer the question, probably that cost the interview. He asked another question to build a matrix from 1 to 100 without repeating any number. I told him to use recursion, he didn't agree.
In a file containing user address and other info find the one with a particular address location
If a number is power of 2
The same keypad question which has already been posted twice. Given 2 = ABC, 3=DEF... and so on...generate all possible sequences for a given phone number...
The same security keypad question which has already been posted here twice or thrice.
Take a date from the user in format mm/dd/yyyy.
Get the number of days between the 1st January of entered date and the entered date.
So if the user enters 23march2010. Print the number of days between 1 January 2010 and 23 March 2010.
Given a string...replace all occurances of a with the.
eg. A quick brown fox jumped over a bridge on a box.
should change to
The quick brown fox jumped over the bridge on the box.
You cannot use the inbuilt replace function for string manipulation.
Given an array like
[3,-6,2,10,-16,5]
Find the max consecutive sum.
Trivial solution is O(n^2).
for i=0 to n
for j=i to n
Find local max for the current i value among j values
Find the global max among local max values.
However I think this sln is not acceptable.
Now it seems to me like a dynamic programming issue.
insertion sort of linked list
how do u find whether two strings are anagrams
recursive function for strlengh
given a set of positive and negative integers group all the positive integers on one side and negative integers on one side...
numbers should be in the same order they appear....
given a string of characters reverse the string (but the characters could be special characters - so a group of char represent
a single special character) Group of chars can be identified by a some connecting characters
g|ss|t
123456 Now g and s are one char group , s and t are one char group
write code for read and write locks
Define a macro for logical XOR operation
what data structure u use for a dictionary - search and insert logic
Find median of two sorted arrays.
write a program to find the center of the tree.
Given an array of integers, for each index i, you have to swap the value at i with the first value smaller than A[ i ] that comes after index i
What is difference between operator overloading and overriding?
Find the angle between minutes and hour hand in an analog clock?
Problem:
Given a board containing 64 squares cover it with peices of paper as small as 1 square and as big as 64 (can be of any shape but should not exceed chessboard boundaries).
If choosen a random square from the 64 squares, what is the least number of pieces of paper is required area to cover the remaining board and their shape? (you can rotate pieces of paper)
Also give a generalized solution for a board of size 2^k.
Find out max sum of the numbers taken out from an array such that no chosen numbers are adjacent. numbers can be negative or positive in given array.
How would you sort a text file full of phone numbers. You do not have enough memory to load all the file contents at once and sort them. You should write back the sorted list to the file in the end.
how would you get two connected components in a graph? how would u represent the graph? detect connected components.
Which one of the following function types CANNOT be overloaded?
1. The constructor function of a structure
2. The constructor function of a class
3. The destructor function of a class
4. Any constant method of a class
5. Any static method of a class”
There can be multiple answers ..
Given a large file where each line contains one sentence(a series of words).
Given a set of input words, print the lines from file where the matching between input words and the line should be atleast 40% or more.
Eg: Input words are "maths" and "science".
The line "maths and science" from the file is eligible as the (no.of.input words matched)/(no.of words in line) is greater than 40%.
The following line "maths is power of world" is not eligible.
A company produces play ball of weights 0-25kg, 25-50kg, 50-75kg, 75-100kg. You need to put the balls in four different buckets daily depending on the number of ball company produces.BucketA (0-25kg), BucketB (25-50kg), BucketC (50-75kg) and BucketD(75-100kg).
A scale is provided on which you can weigh only 1 ball at a time which has a bulb. If the weight of the ball matches the scale category, the bulb will light up otherwise it will be OFF. e.g. If scale is marked to measure 10-25 kg, then any ball between 10 to 25kg (inclusive 10 and 25) will switch on the bulb and say if you weigh 26 it wont switch on the bulb. The cost of scale is 1 million dollar.
Question: You need to find the minimum number you will use to do the job.Also what is weight category you will choose for the scales to do the job.
Input a string and a pattern having . and *
Output: whether the string fully matches the pattern
. match any char, * means matching 0 or more times.
Example:
input "a", "." => match
input "abc", ".*" => match
input "abcd", "a.*d" => match
Input:
Either an object array having integer, string and boolean, like
{"abc", "ab,c", 10, true, false}
Or a hash table like
{"a1":"abc","t":true,"e":123}
Output:
If object array, output
"abc"
10
true
If hash, output
"a1":"abc"
"t" : true
"e" : 123
class A {
int a;
void show(){ };
}
int main()
{
A *obj = new A();
printf("\n object size = %d", sizeof(A));
return 0;
}printf() shows OBJ size 4 bytes ( i.e int size). why Function show() size is not included in OBJ size and where that show() information(i.e.. function pointer and implementation) stored ?.
Is page table per Process ? or KERNEL maintain entire single shared page table for all process ?
Process has some 10 threads and all 10 threads entered DEADLOCK state. How can you free process(threads) from DEADLOCK state ? . Is there any way to kill lower priority thread ? . Can we attach that deadlocked process to the debugger and assign proper value to the Mutex variable ( assume all the threads are waiting on a mutex variable MUT but it is value is 0 and can we assign MUT value to 1 through debugger ) .
How MEMORY TOOLS (Valgrind , Purify ) detects memory leaks and memory corruptions ?. Interviewer asked me to write a function MEMORY_MONITOR() which should provide memory leaks information .
void func( int *p)
{
// Add code to print MEMORY SIZE which is pointed by pointer P.
}
int main()
{
int *p = (int *) malloc (10);
f(p);
}How can we find MEMORY SIZE from memory pointer P in func() ?
#include<iostream>
using namespace std;
int A()
{
return 1;
}
char A()
{
return 'a';
}
int main()
{
int a = (int )A();
return 0;
}Interviewer asked me, is it function overloading? . I said no this not function overload then he asked me why ? ( He emphasized on different function return types int and char ) .
Product of two numbers without * operator and loop
How to find the longest palindrome is a string
Where is this kind of declaration used?
int a[0];Hi,
Had an interv at Microsoft today. Validate IPV4 address is my question..
I have given some logic like split the given by delimiter "." and proceed accordingly to validate each range. Pls input your thoughts. Thanks
1) m * n matrix
2) start from lower left hand cell
3) you can move either up or right
4) find out how many unique paths to the top right hand corner cell.
[][][][][e]
[][][][][]
[s][][][][]
where s= start; e=end;
Given a maze defined in as a two dimensional array, calculate whether a point is reachable from another point. From a point, one can go to either of the four possible directions, but some of the directions can be blocked by wall. This one is pretty straight forward too.
This one is actually quite easy:
Given two linked list, merge them to a single list that will take elements from both list alternately.
[a,b,c,d] + [1,2,3,4] --> [a,1,b,2,c,3,d,4]
Hint: two linked lists can be different size.
1. Given the following code
class A {
X *x;
Y *y;
Z *z;
A(){
x = new X;
y = new Y;
z = new Z;
}
where X, Y & Z are some predefined classes.
if allocations fails at z = new Z; line program will crash. What will you do to prevent the crash without using try-catch.
I was given 2 points a chess board, interviewer asked my to use the as less bit as I can to store those to points, I was thinking to use 3 bits to represent each x and y, then totally is 12 bits, but he was looking for less than that
Hi,
I was asked to write a program to convert decimal to binary without using standard header or library function. sort of embedded situation i guess.
Insert a node each at the begining and at the end of the linked list with same time complexity for both of them.
Design a event driven webserver
func(int* a, int b)
{
while((*a&(1 << b))==0);
}
Why is this piece of code used??
How will you sort 1 million numbers.
Merge sort or quick sort.
better to use c or C++. Why.
Where is the process descriptor structure stored?(Higher 3Gb-4gb)? Is it shared among all processes or separate
Implementation details about a semaphore
DOes linux support semaphores?(he said no..only spinlock)
We are given 4 numbers say n1, n2, n3, n4. We can place them in any order and we can use mathematical operator +, -, *, / in between them to have final result as 24. Write an algorithm for this, it will take 4 numbers and return false or true whether final result 24 is possible with any combination.
what is your cgpa?
what is your name?
Using the following instructions and two registers , A&B.
find out A XOR B and put the result in A
PUSH
POP
NOR
AND
what is problem with this code?#
#include<iostream>
using namespace std;
const int a[]={1,2,3,4,5};
int b[a[2]];
int main(){}
what was your IIT-jee rank
When is a copy constructor called??
3 ants which are at the ends of an equilateral triangle start moving simultaneously in any random direction. what is their probability of meeting??
A stream of numbers coming. How will you store them all so that you can search for any at any time.
I answered use AVL tree. asked the complexity. also i answered Hash map can also be used
What does a c++ code gets from the compiler? I answered enviroment variables he wanted more..i said a default constructor. Grilled me furthur on that.
An sorted array is given with more than one duplicates. You have to remove the duplicates. Can it be done in less than O(n). i tried to think in lines of Bin search but coudnt get it as more than one duplicates
Given a binary tree with nodes with integer values write down the code for calculating the average of the numbers.
Given a shuffle of cards what data structure would you use ? Also tell how would you carry out the suffle operation on that deck such that it is ensured that each card gets shuffled.
Given a shuffle of cards what data structure would you use ? Also tell how would you carry out the suffle operation on that deck such that it is ensured that each card gets shuffled.
Given a binary tree with nodes with integer values write down the code for calculating the average of the numbers.
Given a shuffle of cards what data structure would you use ? Also tell how would you carry out the suffle operation on that deck such that it is ensured that each card gets shuffled.
Given a sum s, and an integer n as an input, find all possible combinations that sum up to s. For example:
If s = 5, and n = 2, then output should be
0+5, 1+4, 2+3, 3+2, 4+1, 5+0
If s = 5, and n = 3, then output should be
0+0+5, 0+1+4, 0+2+3, 0+3+2, 0+4+1, 0+5+0, 1+0+4, 1+1+3, 1+2+2...2+0+3, 2+1+2...5+0+0
and so on for n = 4, 5...
How to merge two binary search trees into a single BST in place?
How to find the number of occurences of a given element in a sorted array?
Given a circular link list.
struct llsit{
int data;
struct llist *nextnode;
};
Node contains alternate +ve and -ve value . Now return the node from where if we keep on adding the values of next node we will always have a +ve sum untill we come to same node again.
Write an algorithm to find factorial of any large number?
How to read the content of .doc,.pdf file in c or java.....
actually this question was arised during discussion of content based searching...
if anyone hav idea pls sujjest....
Write code to print all the possible combinations of the words in a string?
Example:
Input: This is String
Result:
This is String
String is This
This String is
String This is
is This String
is String This
How would you Test Amazon Search Box ?
When we connect a webcam to a PC using USB cable, the system detects the video cam and display the picture.
But assume the scenario where the system didn't display picture even after Video cam is connected.
Write the various reasons to narrow down in not displaying the picture so as to raise a good defect.
Write the valid input arrays for the following function to find the second largest number (Function a[]).
Note: only valid input arrays are required no testdata, no testscenarios or design steps
Write functional & Non functional testscenarios for "Dialog box"
Write a function to reverse a number by eliminating duplicates in it?
Ex: 2452 = 542
Write a function to Reverse a string and Number with out using any inbuilt functions.
Given a list of machines where each machine has a hard disk limit and memory capacity and given a list of processes where each process requires certain hard disk space and memory, write an efficient algorithm to match processes to machines. (You may assume process to server mapping is 1:1).
(I gave a brute force solution but the interviewer wanted a more optimal solution)
1. Given a binary tree print the nodes in this order:
all the left most nodes from top to bottom, then all the leaves, then all the right most nodes from bottom to top, then the root. like
10
5 15
3 2 12 17
you would print 5 3 2 12 17 15 10
21200
01234
here, the bottom string represents the actual numbers(01234), the upper string represents their counts(the same also represents numbers)
so, there are two 0's, one 1, two 0's, zero '3', zero '4'. Find a sequence of length '9' which satisfy this property.
Given two words (that are in dictionary) of equal length how to convert one word to another word so that at each step you can replace one letter in word. And at each step intermediate word also should be in dictioanryDo it with minimum possible steps . '
For example, HEAD->TAIL
HEAD->HEAL->TEAL->TAAL-TAIL
What data structure would you use to pass 1MB of data to OS from network layer for packet delivering?
How does Distance (10-20miles) affect data rate for Wi-Fi networks?
What data struture would you use to pass 1MB of data to OS from network layer for packet delivering?
How does Distance (10-20miles) affect data rate for Wi-Fi networks?
void copystring(char* dest, char *source)
{
while(*source != NULL)
{
*dest = *source;
dest++;
source++;
}
}
int _tmain(int argc, _TCHAR* argv[])
{
char input[10] = "hello";
char *dest;
dest = &input[1];
copystring(dest, input);
return 0;
}
What is the output of the program...
Find output of the following code
int
mingle(int a, int b)
{
int c = b/2;
if (b<=1) { return a;}
cout<<c <<endl;
return a*(b-2*c) + mingle(a,c);
}
int
main()
{
int i;
for (i = 1; i<=5 ; i++) {
cout<<mingle(i+1,i-1)<<endl;
}
return 0;
}
what is cluster in dbms?
load a chapter from a .txt file into memory – split based on paragraphs
Did you faced any stuburn person on your job and how did you handled it ??
implement:
float evaluate(char* s)
for example:
input: "1+2.5" output: 3.5
output: "4-5*8+4/2" output: -34
two rectangles are given. As a struct having {bottomleft-x, bottomleft-y, topright-x, topright-y}
you are given two rectangles R1, R2? determine if they intersect
how will you sort a file which is too large?
Write a Generic Swap Macro in c
Reverse a string using only bitwise operators and without temporary storage.
write a c code for efficient implementation of malloc ....
And then explain
Imagine I am handing you a wine glass and I ask you to test it, what would your steps be?
Given the following: You have an application that consists of three parts: a front end GUI, a middle-ware layer where all the processing of data takes place and a database where data is read from.
What are the areas that would be most likely to break? What would your testing strategy for this be? Why?
I want to create a course registration database for a university. I want to store information for each department, information for each course (including which department they’re offered under as well as which professors are teaching them), information for each professor, and the list of the registered students and which courses each student has registered for.
Keep in mind that an instance of a course could be taught by multiple instructors (i.e. one instructor for the first half of the course and then a different instructor for the second half).
Also keep in mind that there could be multiple instances of a given course offered by different sets of instructors (e.g. offered by Bob Smith on Mondays & Wednesdays at 10am and Bill Jones on Tuesdays & Thursdays at 1pm).
Design a set of database tables to store this information.
I want to create an in-memory definition of an underground city subway system. I want to maintain a list of all of the available stops (i.e. locations) and routes that service these stops. I want to be able to store the schedule for each route. Keep in mind that a given location may be on multiple routes, that a train on a route will visit a given stop multiple times per day, and that each route will have 2 directions.
Design a set of in-memory data structures to maintain this information in memory. I’m not interested in seeing information about how this information would be stored on persistent storage (e.g. hard disk).
I also want to be able to tell a customer how to get from one location to another location and how long it will take them to get there (keeping in mind that it may require them to take multiple trains). Describe how you would fulfill this request with your design.
I want to model the rooms in a house.I want to know what the color and texture of the walls is for each room. I want to know what the flooring material is, what color it is, and the condition of the flooring. I want to be able to call something that returns me the area for each room (you can assume all rooms are rectangular). I want to know how many major appliances are in the kitchen. I want to know how many TV’s are in each room. I want to know for each bedroom if there is an attached bathroom. For each bathroom I want to know if it is a full bath or half bath. I also want to know how many beds are in each bedroom. For all the rooms I want to know if they are heated or cooled and if cooled what is the method of cooling.
Design the class structure to implement this.
Given a stack S, write a C program to sort the stack (in ascending order).
You are not allowed to make any assumptions about how the stack is implemented; the only
functions allowed to be used are: Push, Pop, Top, IsEmpty, IsFull.
There is a sequence of increasing numbers that have the same number of
binary 1s in them. Given n, the number of 1 bits set in each number, write an algorithm
or C program to find the n’th number in the series
You are given have a datatype, say X in C. Determine the size of the datatype,
without declaring a variable or a pointer variable of that type, and, of course without using
the sizeof operator!
Write a C Program to reverse a stack in place using recursion. You can only
use the following ADT functions on stack: IsEmpty, IsFull, Push, Pop, Top
you can not use extra stack or any other data structure
Write a program to find and print the 1500’th ugly number.
Write a method to generate a random number between 1 and 7, given a method that generates a random number between 1 and 5 (i.e., implement rand7() using rand5()).
Given two sets, Write a function to provide the union of them.
You are given a list of Ball objects. Each Ball is either Red or Blue. Write a function that partitions these balls so that all of the balls of each color are contiguous. Return
the index of the first ball of the second color (your result can be Red balls, then Blue balls, or the other way around). In haskell, you’ll probably want to return a ([Ball],Int).
Given an array of integers. The sum of the elements of the array is known to be less than the max integer. Compute the sum.
What if we know that integers are in 2's complement form?
Given a linked list, split it into two lists - one for the front half and, one for the last half. If odd number of elements are
present the extra node should go to the front list
Remove duplicates from a linked list
SortedIntersect: Given two sorted linked lists, create and return a new linked list that represents the intersection of the two
Given a linked list with the following property node2 is left child of node1, if node2 < node1 else, it is the right child.
O P | | O A | | O B | | O C How do you convert the above linked list to the form without disturbing the property. Write C
code for that. O P | | O B / \ / \ / \ O ? O ? determine where do A and C go
You are given: 3 types of vehicles: Motorbike, Car, and a special type of car for the handicapped.
3 types of parking: Motorbike parking, Car parking, handicapped car parking.
Motorbikes and cars can only park in their designated parkings, while the handicapped cars can park either in their own parking or the
regular car parking.
How would you model this as classes? Explain your methods.
Find the missing element in a sorted array in most optimum running time (O(log n))
Given a balanced BST tree, write a function to replace the root with a node that belongs to the original tree.
Given n non overlapping intervals and an element. Write a program to find the interval into which this
element falls.
Design a stack which supports push, pop, min and max operations in O(1).
There is a blank disc. You are given two colors of paint (black and white) . A sensor can recognize the color
painted on the disc and produce an output. Paint the disc in a way such that you can find the direction of
rotation by looking at the output (BWBWBWBW... etc). Find the minimum number of sectors you will need to paint
Write a function to find intersection of two arrays?
An array of size n, has n/2 unique elements and n/2 occurences of an element. Find the
non-unique element in linear time?
You are provided with a stream of numbers, design a data structure to store the numbers in
the stream along with their no. of occurrences.
Count number of lines, characters and words in a file (Given that we don’t have much access
to flashy java methods like readline, String methods like indexOf etc.)
Write a function which takes as parameters one regular expression (only ? and * are the special characters)
and a string and returns whether the string matched the regular expression.
You are given some denominations of coins in an array (int denom[])and infinite
supply of all of them. Given an amount (int amount), find the minimum number of coins required to get
the exact amount. What is the method called?
Given a cube of size n*n*n (i.e made up of n^3 smaller cubes), find the number of smaller cubes on the
surface. Extend this to k-dimension
There are four dogs, each at the counter of a large square. Each of the dogs begins chasing the dog
clockwise from it. All of the dogs run at the same speed. All continously adjust their direction so that
they are always heading straight towards their clockwise neighbor. How long does it take for the dogs to
catch each other? Where does this happen? (Hint: Dog’s are moving in a symmetrical fashion, not along the
edges of the square).
Given two lists write a function which returns a list which is the intersection of the two lists
Three strings say A,B,C are given to you. Check weather 3rd string is interleaved from string A and B.
Ex: A="abcd" B="xyz" C="axybczd". answer is yes.
Given that you can take one step or two steps forward from a given step. So find the total number of ways of
reaching Nth step.
Count the number of set bits in a number. Now optimize for speed. Now optimize for size
An array A[1....n] is said to have a majority element if more than half of its entries are the same.
Given an array, the task is to design an efficient algorithm to tell whether the array has a majority element,
and, if so, to find that element.
The elements of the array are not necessarily from some ordered domain like the integers, and so there can be
no comparisons of the form "is A[i] > A[j]?".
However you can answer questions of the form: "is A[i] = A[j]?" in constant time.
You are given with three sorted arrays (in ascending order), you are required to find a triplet
(one element from each array) such that difference between their positions is minimum
Calculate the Resistance in ohm's that a knights move would require on an infinite plane of resistors
of unit resistance.
Given a set of coin denominators, find the minimum number of coins to give a certain amount of change.
Get the width of a binary tree
Suppose you have an NxN matrix of positive and negative integers. Write some code that finds the
sub-matrix with the maximum sum of its elements.
Given a binary tree with the following constraints: a) A node has either both a left and right child
OR no children b) The right child of a node is either a leaf or NULL write code to invert this tree.
Given the sequence S1 = {a,b,c,d,...,x,y,z,aa,ab,ac.... } and given that this sequence corresponds
(term for term) to the sequence S2 = {1,2,3,4,....} Write code to convert an element of S1 to the
corresponding element of S2. Write code to convert an element of S2 to the corresponding element of S1.
Given N computers networked together, with each computer storing N integers, describe a procedure for
finding the median of all of the numbers. Assume that a computer can only hold O(N) integers
(i.e. no computer can store all N^2 integers). Also assume that there exists a computer on the network
without integers, that we can use to interface with the computers storing the integers.
Write a function that returns a node in a tree given two parameters: pointer to the root node and
the inorder traversal number of the node we want to return. The only information stored in the tree is
the number of children for each node
Write a function to find the next prime number after a given number.
A man has two paper cubes on his desk. Every day he arranges both cubes so that the front faces show
the current day of the month. What numbers are required on the faces of the cubes to allow this for all
possible days in the calendar?
A band is going in the street with a constant speed. Someone in the last row has a dog. The dog runs
ahead, reaches the front row of the band and gets back to it's owner. The dog's speed was constant all
the way and while it was running the band passed 50 feet. Find the length of the dog's path,if the
distance between the front and the rear row of the band is 50 feet.
There are 100 doors in a row that are all initially closed. You make 100 passes by the doors starting
with the first door every time. The first time through you visit every door and toggle the door
(if the door is closed, you open it, if its open, you close it). The second time you only visit
every 2nd door (door #2, #4, #6). the third time, every 3rd door (door #3, #6, #9), etc, until you
only visit the 100th door. What is the state of each door after the last pass?
An apple is in the shape of a ball of radius 31 mm. A worm gets into the apple and digs a tunnel of
total length 61 mm, and then leaves the apple. (The tunnel need not be a straight line.) Prove that
one can cut the apple with a straight slice through the center so that one of the two halves is not rotten.
Given two cubes, how will you represent all the dates in a month
by using numbers 0 to 9?
You can exchange the cubes and rotate them as you wish!!!
You have a machine which can do only multiply by 2, divide by 2 and
Addition of 2 numbers. Write a detailed algorithm to multiply any two
numbers, in this kind of a machine.
Write c++ working code for Given a large number with many digits, propose a method or data structure to
efficiently store them. Addition, subtraction, mult, division should be supported by your design.
Let f(k) = y where k is the y-th number in the increasing sequence of non-negative integers with the
same number of ones in its binary representation as y, e.g. f(0) = 1, f(1) = 1, f(2) = 2, f(3) = 1,
f(4) = 3, f(5) = 2, f(6) = 3 and so on. Given k >= 0, compute f(k).
Compute the discrete log of an unsigned integer.
Given a singly linked list, print out its contents in reverse order. Can you do it without using any extra space?
Given a linked list with the following property node2 is left child of node1, if node2 < node1 else,
it is the right child.
O P
|
|
O A
|
|
O B
|
|
O C
How do you convert the above linked list to the form without disturbing the property. Write C code for that.
O P
|
|
O B
/ \
/ \
/ \
O ? O ?
determine where do A and C go
Given a list of numbers ( fixed list) Now given any other list, how can you efficiently
find out if there is any element in the second list that is an element of the first list (fixed list).
An array of size k contains integers between 1 and n. You are given an additional scratch array of size n.
Compress the original array by removing duplicates in it. What if k << n?
Suppose you are getting an infinite binary stream of characters then after any point of time you need to
print whether the no is divisible by 3 or not, how will you do that?
An array is of size N with integers between 0 and 1024(repetitions allowed). Another array of integers
is of size M with no constraints on the numbers. Find which elements of first array are present in the
second array. (If you are using extra memory, think of minimizing that still, using bitwise operators)
How many matches will be played in a knockout tournament between 9 teams get the general formula for n teams?
design a datastructure to represent the movement of a knight on a chess board
Write an algorithm to traverse a knight covering all the squares on a chessboard starting at a particular point.
There is a temple, whose premises have a garden and a pond. It has 4 idols, each of Ram, Shiv,
Vishnu and Durga. The priest plucks x flowers from the garden and places them in the pond. The number of flowers
doubles up, and he picks y flowers out of them and goes to offer it to Lord Ram. By the time he reaches
to the pond, he finds the remaining flowers also have doubled up in the meantime, so he again picks up y
from the pond and goes to Lord Shiv.This process is repeated till all the Gods have y flowers offered to them,
such that in the end no flower is left in the pond. Find x and y.
On a empty chessboard, a horse starts from a point( say location x,y) and it starts moving randomly,
but once it moves out of board, it cant come inside. So what is the total probability that it stays
within the board after N steps.
Given that you have one string of length N and M small strings of length L . How do you efficiently
find the occurrence of each small string in the larger one ?
You are given with three sorted arrays ( in ascending order), you are required to find a triplet
( one element from each array) such that distance is minimum.
Distance is defined like this :
If a[i], b[j] and c[k] are three elements then
distance=max(abs(a[i]-b[j]),abs(a[i]-c[k]),abs(b[j]-c[k]))"
Please give a solution in O(n) time complexity
Given a Data Structure having first n integers and next n chars. A = i1 i2 i3 ... iN c1 c2 c3 ... cN.
Write an in-place algorithm to rearrange the elements of the array ass A = i1 c1 i2 c2 ... in cn
There is a linked list of numbers of length N. N is very large and you don’t know N. You have to write a
function that will return k random numbers from the list. Numbers should be completely random.
There are a set of 'n' integers. Describe an algorithm to find for each of all its subsets of n-1 integers
the product of its integers. For example, let consider (6, 3, 1, 2). We need to find these
products : 6 * 3 * 1 = 18 6 * 3 * 2 = 36 3 * 1 * 2 = 6 6 * 1 * 2 = 12
How would you determine if someone has won a game of tic-tac-toe on a board of any size?
Given two sequences of items, find the items whose absolute number increases or decreases
the most when comparing one sequence with the other by reading the sequence only once.
How many different binary trees and binary search trees can be made from three nodes that contain the
key values 1, 2 & 3?
Given an expression tree with no parentheses in it, write the program
to give equivalent infix expression with parenthesesinserted where necessary
Given ships travel between points A and B, one every hour leaving from
both ends (simultaneously), how many ships are required (minimum), if the
journey takes 1hr 40 mts. How many ships does each ship encounter in its
journey, and at what times?
Ans 4, 3 at 20 mts, 50 mts and 80 mts.
Count the number of set bits in a number without using a loop.
How would you reverse the bits of a number with log N arithmetic operations, where N is
the number of bits in the integer (eg 32,64..)
Delete a node from a binary tree and balance it. Write code for the former and explain the latter.
Given a maze with cheese at one place and a mouse at some entrance, write
a program to direct the mouse to cheese correctly. (Assume there is a path).
Following primitives are given: moveforward, turnright, turnleft, iswall?,ischeese?, eatcheese.
A car has speed of 72 64 56 in downhill, plain and uphill respectively . A guy travels in the car from
Pt. A to pt. B in 4 Hrs and pt. B to pt. A in 4 Hrs and 40 min. what is the distance between A and B?
Write a program to print the elements of a very long linked list in ascending order.
There may be duplicates in the list. You cannot modify the list or create another one.
Memory is tight, speed is not a problem.
A real life problem - A square picture is cut into 16 squares and they are shuffled. Write a program
to rearrange the 16 squares to get the original big square
There are set of ip address set of the form
10.10.10.10 - 20.20.20.20 -> cable, USA
20.20.20.21 - 33.32.31.30 -> DSL, Germany
.
.
.
250.250.250.250 - 256.256.256.256 -> cable, France
Which indicates all ip addresses between 10.10.10.10 to 20.20.20.20 are of type ‘cable’ and belong
to the country USA, similarly with other ip address set.
Given an array in which elements are unsorted. Write an algorithm that gives two indices n1,n2 such
that if you sort just the elements of the array from n1 to n2, then the whole array will be sorted.
calculate area of a polygon using triangulation method
there was a party.there was a log register in which entry and exit time of all the guests was logged.you have to tell the time at which there was maximum guest in the party.
input will be the entry and exit time of all the n guests [1,4] [2,5] [9,12] [5,9] [5,12]
the output will be t=5 as there was maximum 3 guest were there namly guest(starting from 1) 2,4 and 5.
int i = 4;
switch (i)
{
default:
;
case 3:
i += 5;
if ( i == 8)
{
i++;
if (i == 9) break;
i *= 2;
}
i -= 4;
break;
case 8:
i += 5;
break;
}
printf("i = %d\n", i);
......................
.....................
Why o/p of the code id 5...
pls sujjest
You have to determine whether a polygon contains a point( origin ) or not. Vertex of the polygon are given in cyclic order. Polygon can be convex or concave. Write code( most important part).
You bought a carpet of size n*n, and when you got home you found it has white spots, and black spots (You don't know if it's a white carper with black spots, or a black carpet with white spots). A spot is one or more of the n*n 'cells', or the same color, with either a common side or a common corner. The 'original color' is that of which there are more spots.
for example:
- if the carpet is all white, with a black circle in the middle, it's either black or white (as there is one white spot and one black spot)
- if the carpet is all white with a black, side to side, stripe in the middle, the carpet is white (as there are two whites, and one black spot)
- if it's a 'chessboard' pattern, it's again 1:1 (as each white has a common corner with another white...)
write a function:
int getOriginalColor(boolean[][])
that would return 0 for white, 1 for black, 2 for tie
Propose a data structure that would store numbers, without any knowledge about them, and allow to perform the operations: insert, get median, as efficiently as possible
b. same as before, only this time the numbers are from a group V, which is |V|<<n
A file is given with many 0s stored in continuous way , store it in another file such that when you store try saving the space by using minimum amount of space. When you want to create the original file , you should be able to do so with the new file created. Hint was given so as to utilize the lseek function (a fuction in the Unix)
can use of sparse matrix solve the problem,pls sujjest
1) You have a test application that is issuing asynchronous un-buffered sequential writes to a 15k RPM disk connected through a 3Gb/s SAS interface. The test application is able to get 150 IOPS for an IO size of 8KB. What is the throughput for the writes being issued by this test application?
Tell me how these DS stored in memory?
Hashtables, Dictionary, Trees, Arrays, LinkLists
There is a linked list of numbers of length N. N is very large and you don't know N. You have to write a function that will return k random numbers from the list. Numbers should be completely random.
Bangla numbers
====== =======
Bangla numbers normally use 'kuti' (10000000), 'lakh' (100000), 'hajar' (1000),
'shata' (100) while expanding and converting to text. You are going to write
a program to convert a given number to text with them.
Input
-----
The input file may contain several test cases. Each case will contain a
non-negative number <= 999999999999999.
Output
------
For each case of input, you have to output a line starting with the
case number with four digits adjustment followed by the converted text.
Sample Input
------ -----
23764
45897458973958
Sample Output
------ ------
1. 23 hajar 7 shata 64
2. 45 lakh 89 hajar 7 shata 45 kuti 89 lakh 73 hajar 9 shata 58
Write the clone method of a linked list whose one node point to some random node.
Given 2 linked lists representing numbers such that each node represents digits and head points to the most significant digit, perform addition of these 2 numbers. The numbers can be very large and won't fit in int32 or int64.
eg.
L1 -> 3 -> 2 -> 1
L2 -> 7 -> 9-> 9 -> 8
output should be L3 -> 8 -> 3 -> 1 -> 9there are the k nos of set of words of size n each. write an algo to find the no. of set of anagrams in the given words?
what is run time complexity of the following code...
void fn(int n)
{
int d,i=0;
int j=n;
while(i<j)
{
i++;
d=i*i+(j-.25)*(j-.25)-n*n;
if(d>0) j--;
}
}
A car has speed of 72 64 56 in downhill, plain and uphill respectively . A guy travels in the car from Pt. A to pt. B in 4 Hrs and pt. B to pt. A in 4 Hrs and 40 min. what is the distance between A and B?
Why auto variables are not stored in heap?
Given a file in which the data is stored in the form
ABC
_DEF
_GEH
XYZ
_PQR
__STY
Construct an nary tree out of it in O(n) time such that DEF and GEH are the children of ABC and XYZ is the sibling of ABC, PQR is child of XYZ and STY is child of PQR. The spaces after the beginning of a line specify the relation of a node to its predecessors.
Given a string u have to remove all the duplicate elements from the string and place them at the end of the string.
For Example for the string "abbccddacde"
the output is "abcdebcdacd".
see that abcde are the unique elements and the repeated elements are in the order in which appear in the original string.
Give an O(n) solution for this.
How can one change the value of the Kernel Variables during the runtime?
Today i had a interview with amazon , the question asked was for a n-tree where each node contains any no of nodes print the nodes in level order and each level must contain a line with a gap
Given an array of size n.find 2 numbers from array whose difference is least
I attended MS interview loop this week and I was asked the below question.
Given a IP address as input, validate the ip address.
ValidateIp(string inpIP)
My answer-I validated the characters in the string and then implemented atoi function on each substring and verified for its value in the range of 0-255, I was also asked to assume that an IP can start with 0.
PS: I am not selected:(, not sure if the interviewer knew some other way and expecting me to say the same:)...
Hi All,
I attended MS interview loop this week, I was unable to get through, pissed off after seeing the beautifully madeup regret mail from the staffing consultant, I wanted to share a question and my answer...Beware of the answer as I am not selected:)
here it goes..
Given a text document as input with a set of strings, assume '\n' is the delimiter, print to the console strings grouped by anagrams.
vinay
naviy
inavy
tes
set
...
My answer:
1. sort all the strings and compare...interviewer was not happy with the time complexity of sorting all strings.
2. create a hashtable where the hashcode is generated using the characters in the string..I got the hash of each string by doing an Exclusive OR of each charcater in the string although i had the dbt if the Ex-OR of non anagrams can be same, this is the only other solution that came to my mind.
Any efficient ways of solving this??
Hi All,
I attended MS interview this week, I was unable to get through, but I wanted to share a question for which i failed to give a efficient implementation..any ideas here..
here it goes...
Implement a firewall
prototype:
bool firewall(string url, list<string> IncludedList, List<string> ExcludedList)
Return true if the url is in included list
Return false if the url is in excluded list.
In a ambiguous situation return true\false based on best match.
Included\Excluded Url can contain '*' ex *.com, *.test.com etc...
if input url is www.test.server.com
IncludedLIst contains *.com and if ExcludedList contains *.test.com
Bestmatch in included is .com less then Bestmatch in ExcludedList .test.com..In this case it has to return false..
write a method in java which takes argument as text string and array of token strings and find number of occurrences for each of the tokens in text string.
Design an elevator system, improvise it to multiple elevators with single button on each floor.
given an array of integers, find the 3rd largest integer in it.
Given a Binary tree, write an algorithm to find all the nodes at a distance k from given node n in the tree.
Given 3 product categories and a respective file of a huge size containing only the list of order numbers in sorted manner. Write an algorithm (best possible time complexity to be achieved) which can find common order numbers in all 3 files.
Create methods for Set implementation. (Getting unique values from user to create a Set, and methods to implement Intersection, Union... of 2 sets
You are given the amazon.com database which consists of names of millions of products. When a user enters a search query for particular object with the keyword say "foo" , output all the products which have names having 50% or more similarity with the given keyword ie "foo"
Write the most efficient algorithm for the same.
Print all edge nodes of a complete binary tree anti-clockwise.
That is all the left most nodes starting at root, then the leaves left to right and finally all the rightmost nodes.
In other words, print the boundary of the tree.
Variant: Print the same for a tree that is not complete.
(I traversed the tree twice, but interviewer said there is a recursive way to solve this)
An array is given where each rows are sorted in ascending order and each columns are sorted in ascending order. Like {{1,2,4,6}, {3,5,7,8}}. Now one number "k" is given which can be inside the matrix. Or may not be too.
Need to find out what is the position (i,j) for k, if this is inside the matrix.
Write a program to arrange numbers from 1 to 16 such that the sum of two consecutive numbers is a perfect square
Implement a function
public long[] GetMultiples(int num)
eg if num is given as 30, output array should contain {1,2,4,8,16}. It shouldn't contain 32 since 32 is more than the given number.
Another exp: if num is 300 then output will be {1,2,4,8,16,32,64,128,256}
How do you output the nodes from a binary search tree given a range
Phone screen: Asked a few Windows platform questions like how to create and manage a thread.
Given a char array with words in it, find all 'a' characters and replace with xyz. Modify the input array, do not create a copy of the array.
Given an array of n with each element being in the range of 1-50, print out how many time each number from 1-50 occurs.
Do in order traversal of tree.
Print a tree level by level.
Implement atoi in C.
Input Data : {[1,3],[2,4],[10,11],[4,6]}
Output: {[1,6],[10,11]}
We have to merge all the ranges that are overlapping. You can consider Input data as any Data structure.
A site wants to present lowest airfare for a return journey. Suggest the algorithm to calculate k least sum.
If i say show me 4 options then it should return 4 lowest fares. If 8 then 8 options.
Given a sorted array find two numbers whose sum is equal to the given sum.
E.g 1 2 3 4 5 Sum to find 9 then 4+5 (Just two numbers occurring first and fulfilling the criteria)
what is daemon thread in java
How do we validate that a given doc is a well formed xml? which DS and algorithm? Write the test cases as well
Given a list of strings say N, how would you write a perfect hash function and ensure 0 collissions?
Linked List with following structure..
struct node
{
int data;
struct node *next;
struct node *next_larger;
}initially next_larger of every node is point to NULL.
now write a c code which set all node's next_larger pointer.
where next_largest point to the next larger then its own value and largest value node's next_larger pointer points to NULL
i.e.
if LL is 3->1->5->6->4
then 3's next_larger points to 4
and 1's next_larger points to 3
and 5's next_larger points to 6
and 6's next_larger points to NULL
and 4's next_larger points to 5
if u have a N steps staircase u standing at 1 step now you have options to step up to 2step or you can skip one step and go to 3rd step... so at ith step you have a option to go to i+1 step or i+2 step.. so how many ways you can climb the stairs...??
Q) There is a document containing lots of information. You have a function char * getNextWord() which returns the next word from the document.
a) which data structure should be used for maintaining the information about the frequency of words.
b) Write an effective algo for maintaining the information about the frequency of each word in the document.
c) what is the complexity of algorithm.
Q. There is an array
A[N][M] =
1 2 3
4 5 6
The array is rotated so that
A'[M][N] =
3 6
2 5
1 4
is obtained.
Establish the relation between A and A' by using i, j, M, N
A[i][j] = A'[_][_]
Q. There are two linked list that are sorted. We need to merge these lists so that the obtained list is also in sorted order. You should not prepare an extra list for merging the lists.
The next question was to write the test cases for testing the program.
int main()
{
int i = 32242;
int k = find(i);
return k;
}
int find (int j)
{
if (j > 0)
{
j = j%10 + find(j/10);
printf(" %d ", j);
}
return j;
}Find the output of the program?
Ans: 3 5 7 11 13
you are given 2 arrays sorted in decreasing order of size m and n respectively.
Input: a number k <= n*n and >= 1
Output: the kth largest sum(a+b) possible. where
a (any element from array 1)
b (any element from array 2)
The Brute force approach will take O(n*n). can anyone find a better logic. thnkx in advance.
What type of directory structure is generally used by operating systems?
< As in single level, tree, acyclic etc >
Given an input array of integers of size n, and a query array of integers of size k, find the smallest window of input array that contains all the elements of query array and also in the same order.
In a sequence of integers, find the max length increasing order subsequence.
Find palindrome of max size in a string
Implement a stack which supports FindMin(),push() and pop(). The probability of the occurrence is equal.
find BST of max size in a binary tree
Design parking lot
find the number of occurrence of words at point of time (source is a infinite stream of chars with words separated by space as delimiter)
Print a 2-dimensional array in spiral way(handle border cases)
Given two n digit prime numbers, change the first number to the second by changing one digit at a time. The resulting intermediate numbers should also be prime.
Write me a function that receives three integer inputs for the lengths of the sides of a triangle and returns one of four values to determine the triangle type (1=scalene, 2=isosceles, 3=equilateral, 4=error). Generate test cases for the function assuming another developer coded the function
I have a expression containing extra brackets .Write an algo which can remove unwanted brackets like expression is (((a+d)*(a-2))) so we shuld be able to get (a+d)*(a-2)
Say you need to design a web application which needs to support friends of
friends function(like in linked in, when you search a person, it will show
you if this person is linked with you, your connection or your connections'
conection...), we expect to have millions of users and each user may have
thousands of friends, how would you design/implement this function to make
it scalable.
Given a matrix of integers where every row is sorted and every column is sorted. Print all elements in sorted order.
Cannot use merging of arrays. Solution should be better than O(n2logn)
Given a set of positive and negative integers, partition it into two subsets S1 and S2 such that sum (S1) - sum (S2) = minimum (0 if possible)
A little discussion revealed the problem is NP. But he wanted a solution O(kn) where k is max element in the array
Given is an array of integers. Element is called an extreme if no other element's value is more distant from the average. Write a function
int extreme(int[] A);
that given an array of integers returns the index of an extreme (any one of them if there are many).
If no extreme exists, the function should return -1.
A[0]=9, A[1]=4, A[2]=-3, A[3]=-10
the index of an extreme is 3, because the average of the array is
(9 + 4 + (-3) + (-10)) / 4 = 0
and in this array no value is further from 0 than -10
Write a function
int count_div(int a,int b,int k);
that given three integer numbers a, b and k return number of integers from range [a..b] divisible by k, i.e.:
For example, for a=6, b=11, and k=2, your function should return 3, because there are 3 numbers divisible by 2 in the range [6..11], namely 6, 8 and 10.
You can assume that , and k>0.
Every element in an array of integers points to a relative location from the current element. Precisely, if A[k] = m, the jump from k should land at k+A[k]=k+m.
Write a function
int arrayJmp(int[] A);
that returns the number of jumps until the pointer jumps out of the array when starting from the firstelement.
For example:
A[0]=2, A[1]=3, A[2]=1, A[3]=1, A[4]=3
The pointer's 1st jump is from 0 to 2, 2nd jump from 2 to 3, 3rd jump from 3 to 4, 4th jump from 4 to 7, but 7 is out of the array. The number of jumps until the pointer jumps out of the array is 4.
Return -1 if the sequence of jumps never ends.
You are given an array of positive integers. Convert it to a sorted array with minimum cost. Only valid operation are
1) Decrement -> cost = 1
2) Delete an element completely from the array -> cost = value of element
For example:
4,3,5,6, -> cost 1
10,3,11,12 -> cost 3
What happens if TCP consistently gets timeouts for a given packet? What does it do to maintain reliability?
Lets say you are using UDP to show a live video. Which feature of TCP will you miss the most?
Can you have duplicate packets in UDP?
How will you enhance UDP to have the TCP level of reliability. Basically no packets are lost, duplicate packets are discarded.
How will you implement a monitor in C++?
write your own ArrayList in Java ?
You are given an array ' containing 0s and 1s. Find O(n) time and O(1) space
algorithm to find the maximum sub sequence which has equal number of 1s and
0s.
Examples
1) 10101010
The longest sub sequence that satisfies the problem is the input itself
2)1101000
The longest sub sequence that satisfies the problem is 110100
You have a huge graph of cities and cost of flight between them. Find the cheapest path from A to B. The graph doesnt fit in memory
Given n points in a plane, return k nearest neighbors for all of them. Brute force gives O(n2) but interviewer was expecting something better. I guess O(nlogn)
You are given a 2D array(M*N)containing integers which are sorted. So the topmost element(0,0) is the lowest and the bottom right element is the highest. Given a number find the number in the 2D array.
Given a BST, print all the values >=vmin and <=vmax. Time complexity should be better than O(n). O(logn + (vmax-vmin)) in worst case.
No parent pointers are available
design an algoritm to generate the sequence of positive intergers in increasing order whose only prime divisor are 2 and 3
Can u help me develop algorithm to print the daily salary of workers who each day are paid twice ther previous salary for 30 days
given a word,convert it into a pallindrome with minimum addition of letters to it.letters can be added anywhere in the word.for eg if yahoo is given result shud be yahoohay.give a optimize soln
what is the signature & body of method returning a singleton instance?
Difference between List<String> and List
Given n stairs, how many number of ways can you climb if u use either 1 or 2 at a time?
Given a line segment of length n. You need to cut it into m pieces specified by position[n] array. The price of cutting a segment of length len in two parts is always len (irrespective of cut position). Give a dynamic programming solution to minimize the cost of cutting
5 positive integers are given . In many comaprisons can we find the median.
Asked me about sorting a vector of integers
I told him used std::sort
Then asked me how to sort a vector with objects of class StudentData. I told him use std::sort(ve.begin(), vec.end(), sortRoutine)
The sortRoutine will be define static or global scope in header file.
Given a function: func(CString str1, CString str2). You need to remove all characters in str1 that occur in str2.
Initally i gave him O(n2) solution and he asked me to give more effient one.
So i gave him another solution where str2 is hashed in a hash-map. Iterate through str1 char by char and remove (left shift) the matching chars in str1.
Still he was not happy as the above approach was O(n) + O(m). He asked whether we can do it in O(n). I could not come up with O(n).
How will you protect static data?
How do you make sure that static data is protected well enough.
Explain what you understand by static in C.
Ans. I told him about static variables, static functions. Then he asked me the difference between static class vars and static defined in header file.
Given a dictionary of words and a string with all spaces removed, return whether the string is composed of valid words
e.g
helloworld-> hello world (valid)
isitniceinhere-> is it nice in here (valid)
zxyy-> invalid
Using dynamic programming I got an O(n3) algorithm but he insisted on an O(n2), any idea?
Consider a number 123 , it is ordered since 1<2<3 . Now considering that , generate a permutation of all the possible passwords giving only the ordered sequence.
Suppose a start date is given to be 1 Jan 2000. take the user input as month day and year. Now, the input should be in the form month:03 day:11 year:2010. Now you have to calculate the amount of weeks between the date given and the 01.01.2000 assumed that each year you have 12 months. There is no leap year, and there are 30 days in a month. Now you have to take that week and display the listing of all the days in the week.
A palindrome number is of the format 1234321.
Given a number x, find the smallest palindrome greater than x
There is an array consisting of postive and negative integers. find the subarray whose sum is 0
You have 2 sorted arrays. Return an aray : union - intersection of those 2 arrays
Given a pre-order and in-order sequence , construct a bst out of it..
Given an array of 0s and 1s , in O(n) time and inplace,make all the 0s in one side and all the 1s in other.
Reverse a doubly linkedlist
Check whether the Binary tree is BST or not
Given a binary tree, find a path (from root to a leaf) which gives maximum value by adding values of nodes.
You have single linkedlist.Swap every consecutive two elements without using value stored in the node of linkedlist. for eg. 1->2->3->4->5 then output should be 2->1->4->3->5
create your own atoi()?
Sorted Array is rotated n times. You have to find the current index of the some element X. If element is not present then return the maximum element of the array in O(log n).
You dont know the required size of the array.how will you allocate space for the array.for eg. if you allocate 100 blocks then user can have just 10 elements or 1000 elements.
What happens after entering URL address at the browser(details of how we get to see the web page)?
you have a base class in which you have private data.There is another class which is derived from base class.How will you access the private data of base class from main() by creating object of derived class.
Different ways to do debugging.
What are joins.what is natural join.
you have table employee with salary as one column.there are n rows with maximum salary and x rows with minimum salary.(we dont know n and x). display the difference between total sum of minimum salary and total sum of maximum salary.
You are given ArrayList with n elements in it,on which you can apply on size(),remove(x) operation.size() will current size of the list and remove(x) will remove xth position element. How will you delete alternate elements from the list.
Given a statement which took an integer, incremented it by 1 and then branched to another location which you provide, implement addition of two numbers multiplication, etc using just that statement (or command).
Are there classes in the Java platform library that either is final but you believe should not be, or that are not final but you believe should be?
Suppose you have a file on disk which does not fit in main memory, how will you sort it optimizing time and the number of reads/writes. Mention exactly how many reads/ writes you would need.
4) Given a 3d plane, and infinite points find kth closest point from a given point.
3) Print characters which are present in StringA but not in StringB.
Rotate an array by k units?
Design a parking garage. We spent a lot of time deciding whether Park() method should be in Car class or Garage Class. Any idea?
Now suppose that the parking rate depends on the date and time. How will you store this information?
What is polymorphism? Can you overload the same operator more than once?
How do you think the updates on facebook work? What kind of a data structure do you think they use? How would you be linked to your friends updates?
Design a data structure to store a phone book so that you can search for a phone number using name and vice verse. The solution should be time and space efficient.
difference between static and new operator
Can a Class have a static inner Class?
Write an algorithm to find the absolute max subsequence of an array containing both positive and negative numbers in O(n) time
Eg: {100,-2,300} sum=398
{1,2,3,-9} sum=9
{1,2,3,-4} sum=6
{-1,-2} sum=3
Give an algorithm to compress a memory. To be more clear if you are given a memory of some stored data here and there and some empty and null memory in between, how will you fragment and compress your memory?
Design object-pool
What classes and data structures would you use for a file system?
How do you implement a linked list without using dynamic memory allocation? So basically you need to use an array as a linked list.
implement your own malloc and free for application x, which should control the heap memory usage of the application x.
Give a string, print total count of substrings (length>=2) which are palindromes. He was expecting better than O(n2) time complexity
IBM sells laptops from its website. The total cost is base price + shipping (depends on customer location). How will you design this?
Now imagine millions of transactions. Will you have a separate class per transaction or a single class for all transactions or something else?
You have a binary tree of some shape. Convert it to BST search tree of same shape.
You have a graph with and start point A and end point B. All edges have positive weights. Now the shortest path from A to B can be found using Djikstra.
1) Find the kth shortest path
2) Find the longest path
java:
static void printN(int a, double b) {System.out.println("Print 1");}
static void printN(float a, int b) {System.out.println("Print 2");}
static void printN(double a, float b) {System.out.println("Print 3");}
static void printN(int a, int b) {System.out.println("Print 4");}
static void main(String args[]){
printN(2, 2.0f);
}
Which one will print and why?
write a function isAngram(String s1, String s2) ==> boolean
what's the complexity? how to improve it
Which one of the following statements accurately expresses the disadvantages
of making a function inline?
a) Inline functions always make the program bigger.
b) Inline functions always make the program slower.
c) Inline functions always make the program bigger and slower.
d) It is not possible to take the address of an inline function.
e) It increases compile-time dependencies.
There is a byte array which contains the character of one byte and two bytes. One byte character has range 0 to 127 and first character of 2 byte character is 128 to 255 and second byte character has range 0 to 255. Now, two pointers are given, one points to the start of the and another points to somewhere else.
Tell which character 2nd pointers points to?
Implement Stack with Push() Pop() and Mininum() operation in O(1).
Write a function to find the nearest link on a webpage given the mouse x,y coordinates.
If your algorithm just iterates through all the links, give an idea of how to make it faster.
Given an array of integers as input, filter the array such as to eliminate duplicates(e.g. [1,2,3,2,4,4] => [1,2,3,4]).
Interviewer drew an 2D graph on the board (X and Y axis). Given a set of buildings, defined by (x1,x2,height) discuss an algorithm to determine the silhouette of the buildings (line, the skyline). Buildings can overlap each other.
In C++, write functions for:
string serialize(vector<string> v);
vector<string> deserialize(string s);
such that a string returned from 'serialize' can be passed into deserialize to get the original set of strings back.
Pretend there is a robot that has to navigate a maze (N x M). The robot can only move down or right and the maze can contain walls. Write an algorithm to determine the number of paths the robot can take.
In a single linked list, how to delete a node (no head node given).
Given array of 3 integers. Write a method that returns possible numbers of those 3 integers.
For example: int[] a = {1,2,3}
Output: 12,13,123,321,213 etc..
Write a method that returns 40% A, 50% B and 10% C.
Find repeated number in a sorted array
Write pattern matching algorithm.
i.e isMatch(String,Pattern)
Pattern can have ?(one character) and *(many characters).
ex. abbdef and a?b*f are a match
aaabab and a*ba are not a match
Write a code to implement the Sodoku problem.
Lets say you have a matrix of 9*9 and i can have valued from 1 to 9.
the rules are as below:
1. all the 3*3 matrix shouldn't have any duplicate number.
2. all the rows and columns can't have duplicate numebers.
3. all the diagonal elements in the 9*9 matrix can't have duplicate number.
you have given a node of a tree. that node is defined as below:
node(
int value,
node left;
node right;
node grandparent)
at the starting the grand parent node is null in the tree. you have to assign the grandparent node for all the nodes in the tree.
4th interview with the HR guy:
Asked me about the desired salary.
3rd interview: You are in a maze(like a labyrinth), and you open your eyes so you don't know your position. The maze has walls and you can move only in up, right, left and down directions. You can escape the maze when you find a ladder.
The following API is given:
bool TryMove(direction) - returns true when you don't hit a wall;
bool HasLadder() - return true if you found the ladder.
Write a method bool Explore() that returns true if you can escape the maze, false otherwise. Also, provide test cases.
3rd interview:Given a 4x4 board with pieces in it, find if the board has 4 identical pieces. Each piece has a shape and a color. Two pieces are identical if have the same shape and color. The pieces for this board have 6 colors and 6 shapes.
2nd interview:Given a MxN matrix, in how many ways can you go from top-left to bottom-right?
2nd interview:Serialize and deserialize a tree. (I had to ask some questions until we setteled on rooted tree and the root node was given).
1st interview:Generate a product key for a given product, having this conditions:
1. should be upper roman literals or 0-9 digits;
2. the key should be validated by the installer;
3. how would you check if the key was not registered before?
4. how would you find bad/offensive words in it?(eg. F**K, TIT, T1T...)
sort a linked list in O(n)....
How will you find the page with most incoming links from billions of web-pages
Amazon.com has a link below each product which gives a list of items that "customers who bought this also bought". How will you design that?
You have millions of documents numbered 1,2,3,4,5 ......
You also have a mapping from a word to the list of documents that contains it
Find all the 'pair of words' that occur together in one and only document
Design Farmville,
Consider only crops and animals for now.
Whats classes will you have?
How will you handle interactions between various objects?
What design patterns can you use?
How will you handle millions of users?
What would you do if your Stored Procedure starts performing badly overnight?
Unix script to find the specific string from the given file?
What could be the max value that you can set for jvm -xmx
How to find how much memory your program will need?
Write a program to return distinct numbers from a given list?
Write a program to find if a string is a palindrome e.g aabbcbbaa?
Difference e.g. 10.08 and 10.08-SNAPSHOT in maven?
Difference between mvn intall and deploy?
What is Java Reflection API?
how will u creat own bool data type which can take only true false or 0,1 in C
How to divide a number by 3 without using *, /, +, %, - operators... ??
Write a program to find integer equivalent of a string. E.g : for "121" input o/p should be integer 121
Design a backend for a Chess Application
How will you go about implementing google suggest kind of functionality for a cellphone
How will you go about implementing BlockedQueue with a List
How many string exists of the following form
1) Only characters from 'a' to 'z' allowed
2) No character is repeated
3) Length = 10
4) One and only one character in the string is lexicographically greater than the previous character
For example:
zyxwvutsrq = invalid (0)
zyxwvutrqs = valid! since q>r
A huge file contains unsorted integers. Find the median. The file cannot be loaded in memory
Given a list of Integers,Find the tuple of 3 adjacent elements in this list that adds up to the maximum sum.
how can we find the longest palindrome in the given sentence???
Ex..hello .how are you uoy era woh..
here both 'are you' and 'how are you' are palindromes...but i want to know how to get 'how are you'...the longest palindrome of that sentence.....
How would you explain OOPs to a 10 years old child?
An array is given like {1,4,5,2,3,6,7}. sort the odd elements in descending order and even numbers in ascending order. so result would be
{7,5,3,1,2,4,6}
Prove that you can't build a random number generator function that will output numbers 1 to 7 with uniform distribution and guaranteed to work in finite time using a random number generator that outputs either 1 or 2 with equal probability
Given a number convert it into the roman notation
Given two arrays like {1,2,3,4,5} and {3,2,4,5,1}. Output an array which has the index positions on the elements from the first array in the second array.
So the answer would be {5,2,1,3,4} as 1 from 1st array exists at 5th position in the second array, 2 from first array exists at 2nd position in the 2nd array and so on.
How do you find if onetree is subset of the other?
How do implement Circular Queue?
How do implement Queue using Stack and Stack using Queue
Given two arrays, 1,2,3,4,5 and 2,3,1,0,5 find which number is not present in the second array.
Regression testing,Functional testing and system testing.Explain them and your experience with them?
How would you test a toaster?
How will you remove white space from a string?
find the depth of a binary tree
whats the problem with
list l = new synchronised list(foo)
void foo() {
for (int i =0 ; i <list.length ; i++)
if ( list(i).get. beginswith("a")
list(i).remove;
}
write a code that returns the 5 most common occuring strings in a list
for example list would be something like
"a" "b" "c" "f" "a" "d" "e" "f" "b" "f" "f"
and the function would return
f 4
a 2
b 2
c 1
d 1
Write a preorder traversal of a binary search tree w/o recursion / stack / extra memory storage. Hint - you can augment the node data structure. However, you can't add a visited field to the node.
I will let you guys ponder out a solution before answering with mine :o)
PS: Given the constraints, I believe its impossible to find a fix w/o augmenting the data structure. (If anyone else differs, please enlighten me).
Every object of Polymorphic class, contains a Virtual pointer ( which points to Vtable).
If I have 1000 objects of a polymorphic class,
why should i waste 1000*4 bytes for storing the same stuff...
All 1000 object contains the exatly same value of virtual pointer...
so the question is why can't this virtual pointer could have been kept in class by complier as it keep all the member function definition somewhere... If a class A has member function func1().. there is only one copy of it ...for all the objects... then why do we have separate copy of virtual pointer for each object...while value is same in all the objects ?
How do you think compiler finds the address of a member function for a non polymorphic class?
Don't you think the same mechanism could have been used to find out the virtual pointer for that class also?
I was asked what is the size of an empty C++ class.
class A
{
// No member variable inside
// no member function ( doesn't make //difference anyways)
}I answer that it's One byte.. then i was asked immediately why?
given a complete binary tree (either a node is a leaf node or has two children)
every leaf node has value 0 or 1.
every internal node has value as the AND gate or OR gate.
you are given with the tree and a value V.
you have to output the minimum number of flips (AND to OR or OR to AND) if the evaluated value is not equal to V, if it is equal return 0, if not possible return -1.
you can just change the value of internal nodes i.e can make and to or , or to and to get the desired output
give the minimum number of flips required to get the desired output.
Almost all the interviewers asked about the projects that I worked on and almost all of them expect you to choose the best project that you hve worked and then they ask me as to how tackled that problem........
I was little surprised as I was not asked any Data Structure question on which I had spent lotz of time....
Overall I did very well in 5 interviews......
Interview 3 and interview 4 were like they were trying to dig deep into what I know, and there motive was to prove that I dont what I have learnt and I worked previously.
bool foo(int y)
{
int x;
x = y - 1;
return ((x&y) == 0)
}what is the function of doing? To check if the y is power of 2 or not
int x = -20;
unsigned int y = 6;
z = x + y;what is the value of z?
What is deadlock and what are the 4 conditions that creates a deadlock?
Concepts of critical section and how we use lock and unlock resource to access the shared resource?
what is Amdhal's law?
Asked what is the difference between *p and p*?
Asked to declare a 3-dimensional array
He asked different types IPC mechanisms. Asked when do you use Sockest and when do you use shared memory/semaphore...how do you decide which one to use?
What is priority inversion.. i answered....then he asked why can the higher priority task take over the control instead of lower priority.....
Given a sentence, reverse each and every word in the sentence. I was asked to show all the validations in this prgm. I mean what if there is special character in between the two words. This is exactly what the interviewer was expecting.
Asked about my most toughest project/task in the work experience or school projects.
Find the size of the array ..... He continued to ask about the sizeof() operator
write a prgm for string copy......
write a code of fibonacci series.
Write a C code which returns the position of the first bit set.fot eg. for number 104(1101000) output will be 4.
What is difference between static linking and dynamic linking?
Write a function which takes an integer value as an argument and return its mod 16 value without using these (%,+,_,/) arithmetic operations
You are given a binary tree,how to make this tree such that each node have a next pointer to its next siblings (in the same level).
You are given a binary search tree ,Write a C code to make it a mirror image of the same tree without using any extra space
you are given a sets of words ,Write a C code which output the anagrams sets.eg for i/p: algorithm testing asdfgh esttngi gorialmth
O/p is:
algorithm gorialmth
testing esttngi
Given preorder and inorder traversal of tree, write the code to form binary tree from given traversal.
is there any situation where compiler will not take function as inline(note function is not big)
what is zombie
how to find a child process in unix
what is the most significant advantage of hashtable
what is container
what is allocator
is there any other way of declaring const variables
how can we make sure class object is created only on heap and not anywhere else
what is inline and macro, difference between them
difference between static used in c and c++
memset is sometimes used to initialize data in a constructor like the example below. What is the benefit of initializing this way? Does it work in this example? Does it work in general ? Is it a good idea in general?
class A {
public:
A();
private:
int a;
float f;
char str[35];
long *lp;
};
A::A()
{
memset(this, 0, sizeof(*this));
}
You have a class that many libraries depend on. Now you need to modify the class for one application. Which of the following changes require recompiling all libraries before it is safe to build the application?
a. add a constructor
b. add a data member
c. change destructor into virtual
d. add an argument with default value to an existing member function
Your task is to implement the Reduce function using templates. The Reduce fn applies a function of two arguments cumulatively to the items of an STL container, from begin() to end(), so as to reduce the sequence to a single value. For example, Reduce(<list containing 1,2,3,4,5>, std::plus<int>()) should calculate ((((1+2)+3)+4)+5).
class NotEnoughElements {};
template <typename Container, typename Function>
typename Container::value_type
Reduce(const Container& c, Function fn) throw (NotEnoughElements)
{
Fill here
}
Why does a user-defined swap method(swap using temporary variable) doesnt work even if the variables are of 'Object' type?
What is the difference between Serializable and Externalizable interfaces
On which layer of the OSI model does JVM works? On which layer of the OSI model does Sockets work?
Design classes for Casino Card games. Assuming each game uses all 52 cards. Things to take into consideration: 1 to Multiple decks, shuffling and dealing.
How would you take care dealing when you are running low on available cards in a game that's not continuous shuffling?
Fibonacci Numbers: A number is said to be Fibonacci number if it follows the fibonacci property. (Ex: 112, 1123, etc). But additionally, it need not necessarily start with 1, as with the normal fibonacci series. So, in this new definition, 112(1,1,2) is a fibonacci number and so is 121224(12,12,24), and so is 252550(25,25,50).
So, given any two numbers as input, print out all the Fibonacci Numbers within that range..
Palindrome Date: A date is said to be a palindrome when it is expressed in MMDDYYYY format, it reads the same both ways. Given 2 years as input(ex: 2000, 2010), print out all the dates which are palindrome dates.
Given customer vs visited pages log for three days, find the customers who have visited for exactly 2 days and visited page count > 2. Customer can visit the same page any number of times..
Desing parking lot
Design a DVD rental store. Class diagram.. issues around scalability.
Design Coffee maker .. class diagram
How to represent a map of large nodes and edge in memory
Print elements that are in a vertical column (per column) in a Binary tree
How to find if a binary tree is a binary search tree or not
what are the default members created by the compiler when a class is created.
what is the difference between vector and list
what is the difference between hashmap and map
can we have template virtual functions
what is polymorphism
what is V table
use of static in c++
Given an array A, find A' where every element of A' is product of remaining elements of A.
you have a chat file given than u hav to find no of conversation...
suppose chat b/w me and tom than u hav to find how many time i send msg to tom+how many time tom send msg to me...but do it in c...
what is initialization list and when is it used
what is the difference between vector and list
how Vtable works
what are the default members created by compiler for a class
He showed me a game on his android phone. some sort of maze. There is ball at starting point ball can move in 4 direction at max if there is no wall. End point is hole you need to write code to solve this problem. Idea is convert it into graph and do the DFS to find the path from start to end.
Print the pascal triangle. Don't worry about formating.if i/p is 1 then print first line. if 2 then print 2 lines of triangle.see wiki about pascal triangle.
Write a method echo such that
e.g.
i/p : cat
o/p : catcac
i/p : max
o/p : maxmam
Given a sorted array which contains scores range from 0 to 100. Write a program to find occurrence of given score.
eg. 1,1,1,40,40,40,100,100
input: 40
o/p : 3 (as 40 appear 3 times in array)
what is the difference between hashmap and map
Design a format that describes the pathways you can traverse in the game Zelda.
Difference between const char *p and char * const p?
What is the use of virtual destructors ?
char *xyz()
{
char str[32];
strcpy(str,"Hello there!");
return(str);
}
void main()
{
printf("%s",xyz());
}Given 10K of 16bit integers and unlimited memory, find most efficient algorithm that counts number of bits set to 1.
What is the difference between return statement and exception handling? What are advantages of exaception compared to return statement ?
How will you design the backend for facebook. To handle millions of users. Explain the following transactions
1) Adding/Deleting a friend
2) Friend suggestions
What if you cannot store all users on one server?
You get millions of transactions every day, each transactation has a key. For example Amazon.com get accessed million times a day and the key here is ip address. Find the top 100 users (ip addresses) for a week. The total transaction log is too big for main memory. How can you do it if you have 100 processing servers?
find maximum length BST in a given binary tree.
You are given an array say
5,4,2,7,9,6
You need to convert it to a sorted array in minimum operation where only operation allowed is decrement.
For example above array becomes
2,2,2,6,6,6 (operations=9)
There is a file of 1 GB contains a very big sentence of charecters. It cannot fit in memory
How can we reverse it?
What is the output?
int a[] = { 1, 2, 3, 4, 5 };
const int N = sizeof(a)/sizeof(a[0]);
for (int i = 0; i < N; ++i)
std::cout << (i[a-i]%N)[a+i-1] << " ";Is something wrong in the following code:
int cast(int*=NULL) { return 0; }
Given a array, find k increasing numbers whose summation will be maximum.
Array: 1,5,2,8,7,6,11
k=3
Answer: 5,8,11=24
Thank you CAREER CUP got placed @ AMAZON in campus placements...
Search an Array of string from a file which contains list of words (either sorted or unsorted)
This question is being asked in the careercup chat
Find 2 nodes in a BST with given sum k
Recursion is allowed but no extra space is allowed
Time complexity = O(n)
Space Complexity = O(1)
This was asked in my bloomberg interview.
pure virtual function is one defined as =0;
ex: int foo()=0.
Is following valid ?
class A{
public:
int foo(void)=0;
};
A::foo(void )={};
That is can we have a function as pure virtual function and also have defination like above ?
Justify your answer. If yes, then tell me one situation where we use that.
If not tell me why not.
find the maximum of three integers using conditional operator ?
find error if any??
1. to calculate recursion
int fact(int n)
{
/* error check */
if (n < 0)
return(-1);
/* base case */
if (n == 0)
return(1);
/* recursion */
return(n * fact(n-1));
} I wrote answer wud always be 1 in dis case.... was i correct
write round robin scheduling algorithm with all details and the o/p including ....
--->turn around time
--->waiting time
--->avg tat
--->avg wt
Maze solver problem:
Given a two dimensional maze of square cells measuring 10 cells by 10 cells where the cells are either blocked or empty, we want to know if the maze can be successfully 'solved'.
A maze can be solved if you can move from the top left of the maze (x=0, y=0) to the bottom right of the maze (x=9, y=9) in one-cell steps, within these constraints:
• You can move only up, down, left or right from your current cell.
• You can only move if the cell you wish to move to is empty.
• Diagonal moves or jumps are not allowed.
To encapsulate the problem we define this class:
public class Maze {
private final boolean[][] cells;
public Maze(boolean [][] cells) {
this.cells = cells;
}
private boolean isCellEmpty(int x, int y) {
return cells[x][y];
}
public boolean isSolvable() {
...
}
}
Please implement the isSolvable() method as described.
Given a number find next largest number in a BST implemented as array in constant time.
Two strings are given delete the each appearance of second string in string 1,
ex: str1 "this is a boy"
str2 "is"
so resulting string is "th a boy"
Write a program to merge the two sorted link list ?
What are your strengths?
given a matrix pxq
You start from top left and have to reach the bottom right. Can only traverse right or bottom
How many ways are there to reach at the bottom right?
How do you lock a file on unix platform (solaris)?
My answer was:
open (FILE, 'file-name');
flock FILE, 2;
# Do everthing here
flock FILE, 8;
close(FILE);
But interviewer told me that the solution does not work on unix platform.
After the interview i tried running the code on Solaris machine and it did not lock the file :(
1. Write a function that takes an array of five integers, each of which is between 1 and 10, and returns the number of combinations of those integers that sum to 15. For example, calling the function with the array [1, 2, 3, 4, 5] should return 1, while calling it with [5, 5, 10, 2, 3] should return 4 (5 + 10, 5 + 10, 5 + 5 + 2 + 3, 10 + 2 + 3). You may assume that the input has already been validated. Show how you would test this function.
Given a input string find the longest substring which appears more than once in the string?
Given two sorted positive integer arrays A(n) and B(n), we define a set S = {(a,b) | a \in A and b
\in B}. Obviously there are n2 elements in S. The value of such a pair is defined as Val(a,b) = a +
b. Now we want to get the n pairs from S with largest values.
Given an array of size n wherein elements keep on increasing monotically upto a certain location
after which they keep on decreasing monotically, then again keep on increasing, then decreasing
again and so on. Sort the array in place (ie. using only O(1) extra memory).
Find if a string is a substring of another. Note that a mismatch of one character
should be ignored. A mismatch is either an extra character (’dog’ matches ‘xxxdoogyyyy’), a
missing char (’dog’ matches ‘xxxxdgyyyy’) or a different character (’dog’ matches ‘xxxdigyyyy’)
Generate all strings of length ‘n’ which do not contain a given string as a substring.
why cant union in c++ have a static data member or virtual function?
Print all permutations(anagrams) of a string without any repeatation
Given an array of n elements and an integer k where k<n.
Elements {a[0].....a[k] and a[k+1].....a[n] are already sorted. Give an algorithm to sort in O(n) time and O(1) space.
Given n number of points in space and a point P, find 3 nearest point to p
You are given a set of n points in a XY plane. Suggest an algorithm to determine if every point is at least separated by every other point by a Manhattan distance of 5 units. Return should be true or false.
Simplest option is to check each point with every other point to see if (x1-x2) < 5 && (y1-y2) < 5. But this would be O(n^2). But they expected a solution with lesser complexity.
write code to find maximum and 2nd maximum number in an array.He was interested in tournament algo.
Write a C function for unsigned power(double x, unsigned int n) using minimum number of multiplications. Count the number of multiplications used.
Given a circular road and a set of petrol pumps located at distances d1 d2 ... dn away from each other and supplying p1 p2 p3 ... pn amounts of fuel and your vehicle has a mileage of 1km/l. Determine the feasibility of going around the path starting with zero fuel. Find a point from which you can start and complete the cycle given that you have zero initial fuel.
You are given a dictionary of all valid words. You have the following 3 operations permitted on a word: delete a character, insert a character, replace a character. Now given two words - word1 and word2 - find the minimum number of steps required to convert word1 to word2. (one operation counts as 1 step.)
Consider a n ary tree. Print the output a follows
1
2 3 4
8 4 5 6 7 9 10 11 12
Output:
(1(2(8)(4)(5))(3(6)(7)(9))(4(10)(11)(12)))
Given an array of integers. Imagine it as a pyramid as below:
a[]={1,2,3,4,5,6,7,8,9,10}
1
2 3
4 5 6
7 8 9 10
find a path from level 1 to last level such that the sum is maximum. The path is such that its children should be reachable.
Ex:
1,2,5,9 is a path
1,2,6,10 is not a path since 6 is not reachable from 2.
The array is not sorted and numbers are random.
Given a set of schedules with Start and End times, cluster the ones which have a collision in time. The clusters can have more than two schedules and have to be unique. Do it efficiently.
Given a large set of balls say N such that these balls are identical if they are of the same color. We have to randomly pick one of the balls such that the probability of picking is the same. Find an efficient way of solving this in terms of space and running time complexity.
find the output of the following code:
//assume all header files are declared..
#define concatinate(a,b) a##b
#define same1(a) #a
#define same2(a) same1(a)
int main(){
printf("%s\n",same2(concatinate(1,2)));
printf("%s\n",same1(concatinate(1,2)));
}
The private member in derived class
Answer: Can be inherited only if the derived class is inheriting from base class with private access level
This is an on-line test. I don't know what the answer means.
Using pointers to call a function is called as
Answer: call by reference
This is an on-line test. I don't know why the answer is call by reference
Write a function to determine if a tree(need not be binary) is a BST.
Write a function to determine if a binary tree is a BST.
write a function boolean substr(String string, String substr) where substr function returns true if substr is a substring of string.
sort the input array. only following operations on array is allowed:
1)get(index) -gets the element at that index
2)reverse(int start,int end) - example reverse(1,3) for the array [1,2,3,4,5] will return [1,4,3,2,5]
A specification for a very simple file system stored inside a flat file (FS). There is an associated index file (FI) which provides meta-data to the data inside the flat file (FS).
FS:- FS cannot be larger than 1 MB. The entire space in FS is divided into blocks of 128 bytes.
FI:- FI provides meta-data regarding what is stored in FS. Directories, sub-directories and files are supported. Files can be binary or text which is marked in the meta-data. The following is a detailed description of FI-
FI consists of a sequence of entries or records. Each record (R) is 48 bytes long. Each record has an index and is referred by its index. There can be a max 8192 Records if each file is exactly one block long. Therefore FI can be at most 8192 x 48 = ~384KB in size. The structure of each R is -
1 2 3 4 5
|-----------------|--|--|---|-------|
1 Name (32 bytes)
2 Attribs (2 bytes) Described below
3 Directory Entry (2 bytes) - what is the parent directory of this record
4 Size (4 bytes) File size, 0 for Directory
5 Blocks list (8 bytes)
Name The file/dir name can be at most 32 bytes long. Only ascii alpha-numeric characters are allowed. The only symbols allowed are - $ and . A string shorter than 32 characters is terminated with an ascii value of 0.
Attributes Only the relevant attributes are described here
1st bit if set is a File else Dir
3rd bit if set is a Text file else Binary
Dir Entry The index of the parents Record in FI. The root entry has this value as 0.
Size - The actual size of the file (not the block count), always 0 for directories
Blocks list - Lists which blocks in FS holds the contents of this record. 8 bytes allows for 4 block indices to be specified each of size 2 bytes. If a file is larger than 4 block sizes (i.e. larger than 512 bytes) then a chaining mechanism is used where the last 2 bytes of the block from FS is used to point to the next block in FS. Suppose if the file is of 8 block size, then the last 2 bytes of 4th block will point to 5th block and last 2 bytes of 5th block points to 6th block and so on.
Directories will not have any block entries.
The root directory always occupies R[0].
Problem
A] Write a class com.progress.test.FSReader which has a static read method and takes as its only argument a file path similar to \files\abc.txt and returns a String of its contents. If the path provided is not a file or not a text file null must be returned. No exceptions must be thrown.
Signature -> String com.ma.test.FSReader.read(String path)
For test purposes, you can use file path \ma\ProblemStatement.txt which returns present file contents.
Demonstrate memory leak.
How do you delete the object of a singleton class?
Using pointers to call a function is called as Answer: call by reference
This is a multiple-choice question from on-line test. The statement above is a correct answer but I don't know why it is called call by reference.
The private member in derived class can be inherited only if the derived class is inheriting from base class with private access level
This is a multiple-choice question from on-line test. The statement above is a correct answer but I don't know what it means.
Using pointers to call a function is called as Answer: call by reference
This is also multiple-choice question from on-line test. Anyone knows why it is called call by reference?
The private member in derived class can be inherited only if the derived class is inheriting from base class with private access level.
This is a on-line test. The statement above is a correct choice. But I don't understand what it means.
Write an Algorithm to find Level Sum and Store that in an Array??
eg
5
/ \
3 8
/ \ / \
1 4 6 10
for this tree a[0]=5,a[1]=11,a[2]=21.....
A Jar
A fly that replicates at 1:2 (One fly becoming 2}
Takes a minute for replication.
If the jar is filled(100%) in 60 Mins.
At what time it will be filled with 75%.
B-Trees
- Their Structure
- Search Complexity
C++ Variable Scoping
- Local
- Global
- Dynamic
R = Red
B = Blue
I/P - An fixed array { R, B, B, R........}
O/P - array { R, R, R..........B.........}
Catch:
Consider corner cases
1. All B
2. All R
Find out the Nth largest number from last end . Let's suppose you are performing this operation in BST.
ex:
5
/\
3 7
/\ /\
1 4 6 9
int findlargest(Tree *t,int n)
int a = findlargest(Root,2)
O/P : a = 6
you are given a matrix with lowest left corner as starting point(1, 1) and the upper most right corner as the end point(m,n).Each element of the matrix is having some weight. while traversing from (1, 1) you can go one cell in the right or you can go one cell up.
Questions:
a)What is the total number of paths between (1,1) to (m,n). (note:you have to write only a mathematical expression in this part.)
b)Write a program to find the costliest path,also return the path length.
Complexity should be in polynomial time.
for example one path from (1,1) to (m,n) may be as follows.
- ------- ---------
| ^-> (m,n)|
| | |
| ^ |
| ^->->| |
|_(1,1)->| |
---Given a book find out the number of times each word appeared. Upon clarification I was told the following things 1. punctuations should be removed 2. case sensitive 3. assume book is given as a huge string to the function prototype 4. Words need not be ordered in any way
The first phone screen the guy asked a question from programming pearls, how do you find all the anagrams in the dictionary.
Which is the best data structure to hold multiple keys for multiple objects
ie each object have multiple keys
Given a pointer to the node, the node has one data part and two address pointers of its own type,
If the node represent a doubly linked list convert it to B-Tree and vice versa.
Write test cases to check the system
Given a singly linked list sorted in ascending order, convert it to a height balanced BST from this.
Given a text file, implement a solution to find out if a pattern similar to wild cards can be detected.
fort example find if a*b*cd*, or *win or *def* exists in the text.
Design the data structure to provide the mathematical operations +, - ,/ , * etc for the very very large numbers.
also implement the + function for two such very very large numbers ...say numbers with 1 Million digits.
{a} There is a string S ans another string s1,
Design the algorithm to check if s1 is contained inside S and return the location as well.
Hint: Interviewer told me that this is a standard problem from book,
{b} test cases to check this.
Provided a array of size 100 stuffed with ONLY 99 values from 1 to 100 ,SO array size is 99 now .
How can you find the 100th value in that array ?
Answer is Mathamtic Progession .
Add 1 to 100 Lets say X
add 99 elements in array Lets say Y
X - Y is our answer .
Testing a text box.
Testing a object(paper weight) kind of question.
implement File.Copy functionality in C#
find the maximum subsequence sum in a linked list. Consider the node as shown below.This node class has a extra item isvertex which determines whether the node is a vertex r not.
so find the longest distance between any 2 vertex in the linked list.
Node SLL{
int data;
Node n;
bool isVertex;
}
How to find the missing K elements out of the unsorted natural N elements in an integer array.
Time complexity has to be O(n), with 3 extra variables of Space.
Given an array of size n.find 2 numbers from array whose difference is least.
Cyclic shift by K the given array of length N in the best time and O(1) memory.
Remove unnecessary from an expression :
1) (((a))) => a
2) (a+b) => a+b
3) (a+b)*c => (a+b)*c
4)(((a+b)*(c+d))+e) => (a+b)*(c+d)+e
char* NewLine(char* s)
{
char buffer[1024];
l = strlen(s);
strcpy(s,buffer);
s[l]='\n'; // Add a new line character to s;
return s;
}
What is the output? What is the problem with the code if any?
Suppose you a have function which returns a word char* GetWord() from a document. Write a data structure which holds the words in the most efficient way. If the words are repeated, find the number of repeated words.
a)What data structure you used?
b) What algorithm you implemented?
c) What is the level of the algorithm.
Merge two linked lists: Node* MergeList(Node *list1, Node* list2). Do not create a node in the function while merging the lists.
Struct Node{
int data;
struct node* p;
}
. A's population is 68000 and it decreases by 80 per year. B's population is 42000 and it increases by 120 per year. After how many years both cities will have same population?
Sum of digits of a 2 digit number is 8. When 18 is added to the no, the digits gets reversed. Wat is the
. Successive discounts of 20% and 15% are equal to a single discount of ?
write code to print an upper trangular array.if ni of line is given as 4
write code to find second highest value of an integer array using a single for loop.
Write a program to print an unsigned integer that is greater than a given unsigned integer but has the same number of 1's in binary form.
You are given n strings. You have to find whether a chain can be formed with all the strings given namely n ?
A chain can be formed between 2 strings if last character of the 1st string matches with the first character of the second string. Also print the chain numbers
Count the number of Bits that are set in a floating point number
Can someone tell me abt the written test of AMAZON for campus placements..
You have an array like ar[]= {1,3,2,4,5,4,2}. You need to create another array ar_low[] such that ar_low[i] = number of elements lower than or equal to ar[i] in ar[i+1:n-1].
So the output of above should be {0,2,1,2,2,1,0}
Time complexity : O(n)
use of extra space allowed.
given a string find the number of distinct substrings of the string.
ex:
input-> aaaa
output-> 4(a, aa, aaa, aaaa)
input->abcd
output->10(a, b, c, d, ab, bc, cd, abc, bcd, abcd)
Given a array A[] and a number x, find the subarray who's sum is equal to x. A[] contains both positive and negative numbers.
Given a set T of characters and a string S , find the minimum window in S which will contain all the characters in T in complexity O(n) .
Find the least common ancestor .
How to do level order traversal using recursion ?
How to calculate sum of levels in binary tree ?
Write an iterator that returns 10% true and false otherwise. The interviewer was not at all clear about the question and eventually skipped the question when asked more about it.
. A single threaded Win32 GUI application has multiple top-level windows. In a message handler for one of the windows, it displays a modal dialog (for example, by using the MessageBox function). The other windows in the application still work as usual, even though the only thread in the application is waiting for the modal dialog result.
Describe how this behavior works.
give an example of an application a binary tree is used for
What is the difference between function overwritting and function overloading
There is an array with odd elements, and we know beforehand that only one element occurs odd times. Other elements are replicated even times in the array. How to find that single element? Extra requirements: Using C to implement on the whiteboard and propose test cases.
Excel labels its rows with letters. For example row 0 is labeled 'A', row 1 is labeled 'B', row 26 is labeled 'AA', and so on.
Design, and implement in C, an algorithm that will map any row number, such as 2842, into into its proper row designation. For instance row 2842, maps to the designation 'DEI'
How to merge K sorted list in O(N*log(K)) time, Each of list has N elements.
sorry... Here N means the total number of elements .
Write a Code to merge N sorted array.
Input integer iIn is given as input.
Output is also an integer iOp.
The string must contain only the following characters.
'A' and
'B'
The string formation must follow these rules.
1. The number of A's and B's in the string are equal.
2. For any prefix of the string, the number of A's must be greater than or equal to
the number of B's.
Given iIn, then find the number of possible string which match this criteria iOp.
Eg,
AB
ABAB
AABB
AAABBB
ABABAB
AABBAB
...
Any suggestions towards solving this question is welcome.
A Brute force method can solve the problem.
But when the input becomes larger, the algorithm might eventually get slow. So a better solution is to be
suggested.
Given a text file and a function getNextWord(), which returns a next word read and NULL if EOF is reached. A comparison function to compare two strings bool isEqual(char* str1, char* str2) is also given. Create a link list, which has following node type : struct Node{
Node* next;
int freq;
char* str;
};
The list must be sorted according to freq and algo must work in less than O(n2).
what are the various ways to terminate a process by itself normally and abnormally. Also the ways to kill the process by another process in unix
What are the different file types avilable in unix system
Write a funtion to find out longest palindrome in a given string
Write a program to print all the combinations of a given array of elements.
Implement linkedlist operations without using pointers. They want all the operations of linkedlist like add at any position or delete at any position to be supported
what s the name of the doubly linked list with no data field.............
A graph is given. You need to design a data structure with minimum space complexity such that it does the follows
--> Finds whether nodes u and v have a path in between them in O(1) time.
--> Finds whether there is a path of length k between u and v in O(k) time.
The same data structure to be used for both the purposes.
I was interview for a Test lead. There were 6 round in total and all the rounds were as expected and question which were asked were as expected, like given a scenario how would you test.
This algo question I was not able t crack so, posting it.
There is an array (with +ve integer) we need to sort the array ONLY with the help of the following function.
Flip(Array a, int size, int flipPos)
so if the array is
a = 3,2,6,8,1,9
and i call
Flip(a, 6, 3)
then a = 6,2,3,8,1,9.
Any ideas in how to proceed.
He told me that you can find the largest or smallest element on o(n) time and then go ahead wth that.
Thanks.
Design a elevator
How will design an algorithm to get Least Recently Used (object) in a Cache {see LRU Cache in wiki}
Implement stack using two queues.
Sort a stack using recursion.
what are volatile and transient modifiers??
Input : Two large singly linked lists representing numbers with most significant digit as head and least significant as last node.
Output: Difference between the numbers as a third linked list with Most significant digit as the head.
Eg:
---
Input:
A = 5->4->2->0->0->9->0->0
B = 1->9->9
Output:
C = 5->4->2->0->0->7->0->1
Required complexity :
O(n)
Constraint:
Reversing linked list is NOT allowed
What is the difference between dynamic loading and dynamic linking??
Given a boolean matrix with all the true elements on left side in the row so that each row can be broken into two parts left part containing only true elements and right part containing only false elements. Find the row with max number of true elements in it.
Given a root and a node of a binary tree, write a function which finds all the nodes which are a 'k' distance from the given nodes. (distance can be upwards and downwards)
Given a normal dice and a dice with blank faces, fill in the blank dice with numbers from 0-6 so that the probability of each number coming up, when you roll the two dice together, is equal.
static functions can call only other static functions and static variables then how does public static void main(String args[]) function is successful to call non-static functions and also non static variables?
How to find no. of times each character is repeated with less time complexity..
[2] There is a bank which give the 100% rate of interest (annual). you have 1 dollar today with you and you deposit that in the bank.
after how much time would you become the richest man.
[1] Design a layer in front of a system which cache the last n requests and the responses to them from the system.
what data structure would you use to implement the cache in the later to support following operations.
[a] When a request comes look it up in the cache and if it hits then return the response from here and do not pass the request to the system
[b] If the request is not found in the cache then pass it on to the system
[c] Since cache can only store the last n requests, Insert the n+1th request in the cache and delete one of the older requests from the cache
The objective is to achieve all the three operations in O(1).
How will you sort 1 million floating point numbers?
Write a chunk of code in Java which shows an example of deadlock.
Write a URL shortner (like tinyurl) . Take a URL as input & return a shortened URL. If you use any kind of storage or persistence, please use the appropriate api's of the language. Another requirement is that we want to make our URLs as different as possible, so that successive calls return very different URIs
This is to ensure that small typo errors do not lead to users getting to a valid URL, but rather throwing up an error page.
What Data Structure will you use to implement a garbage collection engine?
Given a BST and a node value, find the mirror node of the node containing that value.
Given a Tree, verify that it is a binary search tree. (input not specified as a binary tree, just a tree)
How would you Implement an LRU Cache?
Suppose in your first week of joining Amazon you come across a customer who says he has a problem. your team member is on leave and the problem is there is a reader which is reading labels and classifying packages. this reader is misclassifying. how do you handle this.
the reader is third party. labels are ours
we need to corner the problem
solve the following design problem: we have n instances of a service s1, s2, s3 ... sn running. And there are m orders o1, o2, ... om and whenever i % n + 1 = j, the order goes to service sj
what are the problems ?
how to solve these problems
Write an algorithm to find the duplicates in two unsorted arrays
Design classes for Themes in UI. A Theme has a font, background colour, background image etc.
Memory is an array R[1..n]. And a Block is essentially all memory between two indexes i, and j. Now, each application uses some blocks. And blocks can be contained within one another or can be disjoint, but they cannot be intersecting otherwise. So in this scenario, write an algorithm to lock or unlock a block. if a block is locked, none of its child blocks should be allowed to be locked and none of its parent blocks should be allowed to be locked.
In Amazon 100 million queries for various objects can arrive at a database . This can cause bottleneck. Design a system for this.
how will you find a maximum path in a graph
In our website, people enter addresses. Each address is made up of some lines. And each address can be represented as rows in a database. how would you design a system which would verify if the addresses are valid or not, that is if the address really exists or not.
When an employee joins amazon , he has to go through various departments. like the admin department, finance etc. you have to create a design for this.
Given a two strings, determine if one is a circular permutation of the other or not. For example abcd, cdab are circular permutations
Stock prices are given to you at various time intervals. p1, p2, p3,... you are allowed to buy and sell only once each. So write a program to find the index where you would buy and where you would sell to maximize profit
Given a number line 1734, how to return the next higher permutation of its digits
input is n, find the no. of 0's at the end of n! [factorial of n]
Explain about hashing. Give one example of a hash function and explain how collision is handled.
I want to create a LRU [least recently used cache] such that push, pop and find min [without deletion] are done in constant time how to do this?
Design a Train & reservation system. Give class structure and design
UML
Given an array of n elements such that one element repeats n/2 times and rest of the elements are distinct, how to find the repeating element ?
You are given a sorted array that is rotated circularly from a particular point. for example 12345 rotated about 3, circularly is 34512
you have to search for a number in that list
in O(lgn)
What should be the test strategy for testing a text engine?
Amazon.com has the feature that if users search for particular CD or books etc then it also tells what other related books/CDs users bought.
Example, if a user search for the book "Introduction to Algorithms" then it also shows users who bought this book also bought "Robert Sedgewick - Alogrithms in C++" or "Fundamentals in Data Structures".
Assuming everything is maintained in memory & file system what algorithm will give this set of related intersection/connection ?
there is 1000*1000 matrix each row is filed with 0 and 1 . left 1 right 0 once a 0 come thn 1 cannot come..
U have to find out the row which has maximum 1 and no. of 1 in that row..
This thing hav to do in complexity O(n+constant)
u hav root a node address and length is given
u need to find all the node frm give node which can be reachabe upto the given length. It can be left or right or top of node. but tree is simple binary which donot hav parent link
Implement a phone book.
1. u can search either by name or phone number.
2. u can serach by prefix also.
3. They want to write whole code with proper syntax..
I told its possible by hashing thn i come to tri... but whole code is too big to write. I almost took 1.5 hour to write
What is stack. what are the things that go in stack and in which order??
What are zombie processes. how can we create a zombie process.
Prove that any permutation of 1-100 natural numbers will have at least 10 numbers in increasing or decreasing subsequence.
main()
{
int x=40;
{
int x=20;
printf("%d",x);
}
printf("%d",x);
}
What is the output??
how to convert a queue into stack
how to perform permutation...
Asked about zombie processes. What happens underneath when a unix shell executes a command in background (e.g., "gcc foo.c &")
(Hint: we talked about SIGCHLD signal, signal handler, waitpid, return value of a process, etc)
What is bridge pattern? Asked me to write skeleton of bridge pattern.
There are different types of GUI themes, and there are different types of buttons. When a user pushes a button, its outcome depends on the type of GUI theme selected, and the type of button pressed. Discuss your design approach.
(Hint: double dispatch)
Asked a design problem where observer pattern fits perfectly.
Asked about RAII, auto_ptr, shared pointer.
Can we have containers of std::auto_ptr?
Whats the use of reserve() method in vector? How does vector compare to a deque in terms of performance of push_back()'s.
What are the implications of doing a fork() from one of the threads of a multi-threaded process? Does child process get all threads of parent process?
Lets say you have a unix shell, and you type a unix command, say, for example "ls". What happens at the system level? (basically asking about fork() and exec() )
Implement the function bool isRegex(char *reg, char *string); This function is passed two strings : a regular expression, consisting of the [a-z] and the * and ? characters. We had to check if the string matched the supplied regular expression. For example, if reg is a*b, and string is acbcb, we should return true. And if reg is a?b and string is accb, we return false....
(P.S. this is question asked to someone else...but i want to know a efficient solution)
Implement the function : node * add(node *l1, node *l2). The lists L1 and L2 are linked lists where each node of the linked list contains a single hexadecimal digit, represented as a char. The whole list thus represents a hexadecimal number. We had to add the two hex numbers represented in l1 and l2, and return the head of the linked list representing the answer.......don't use list reversal..
Ex.
number 1234 and 2345
1->2->3->4->
2->3->4->5->
(asked atleast for decimal number without reversal)
You are given a dictionary of all valid words. You have the following 3 operations permitted on a word:
a) Delete a character
b) Insert a character
c) Replace a character
Now given two words - word1 and word2 - find the minimum number of steps required to convert word1 to word2. (one operation counts as 1 step.)
3 different boxes hold different amounts of items. How do you pull from them proportionally? Now create the code.
How would you develop code for a system with potentially 10,000 different integer cases? For instance, using credit card numbers the range of 0-25,000 would be MC, then 30,000-50,000 would be AMX, and so forth. There could be 10,000 types of cards though.
How to find the square root of a perfect square number in O(log n) complexity??
Explain the difference between StringBuffer and StringBuilder. Why would you use each?
1. A* a=new A();
2. A b;
A *c=&b;
What is the difference between 1 and 2?
void foo(A a){}
A* a =new A();
foo(*a);
A b=*a;
b=*a;
How many copy ctors of class A are called?
How do you implement find command in Unix? Which data structure will you use?
Program to find the endianess of the machine
3. Program to find the middle of the linked list.
2. Program to test if a number is power of 2.
1. Program to find the number of bits set in a byte.
Explain the difference between Shallow Copy and Deep Copy.
Given a 2D-grid map with several obstacles such as walls, doors and ones with other shapes, use A* algorithm to give the robot a path from point A to point B with fewest turns. Probability might be used in this problem.
Why any iterator method can't contain any ref/out agrument?
How to create an array of objects which doesn't supply default constructor?
Difference of behaviour, when calling virtual method in constructor, between C++ and C#.
There is a parking lot of cars that is full except for a single spot. Write some code to take it from one arbitrary configuration to another moving only one car at a time into the empty spot. Analyse the time complexity, how would you improve it, etc.
2nd phone interview: This was a design question. Basic idea was that there were many clients who wanted to be updated whenever certain items arrived in Amazon's store.
Hint: This is classic pub/sub (observer pattern). Discussion involved multicast, kind of data structures to be used, where will the state of the system be maintained, memory optimization, etc.
2nd phone interview: Given a sorted array which has been rotated (e.g., 5, 6, 1, 2, 3, 4). Find the index where array is rotated (i.e., index of 1 in the example). Do it in O(log n).
1st phone interview: Given an array of numbers (not sorted). Find two numbers in the array whose sum is equal to a given number, in O(n).
Hint: Use hash table. Lets say given number is N. For each number a[i] in the array, store it in the table, along with its compliment i.e., N - a[i]. First collision is your answer.
1st phone interview: Discuss object oriented features of C++.
public string impossible()
{
try
{
// Person is a reference type
Person person = null;
return person.FullName;
}
catch (NullReferenceException)
{
return string.Empty;
}
}
Could method `impossible` ever return a non-empty string? If yes, in which cases.
When C++ compiler can't generate default = operator for the class?
Give an unsorted array find count of pairs of numbers[a,b] where a > b and b comes after a in the array.
Eg. {8,3,6,10,5}
the count of such numbers is 5. i.e. (8,3), (8,6), (8,5), (6,5) and (10,5)
how to find cycle in graph
Given a Binary Tree in the form of grid. For example,
{ 1}
{ 2 3}
{ 4 5 6 7}
{ 8 9,10,11 2,13,14 15}
You can see a grid here, such that the first column in the grid contains the first column value 8, second grid column contains ,4 alone, 3rd grid contains, 2,9,10,11, 4th grid contains, 1,5,6. 5th grid contains 3,12,13,14, 6th column contains 7, and the 7th column contains 15. Please note that, the tree is not a complete binary tree . The one thing I remembered was a pascals triangle from this, But, i could not device an algorithm to find the sum of each column of the grid. Another procedure that came to my mind is, to build a complete binary tree out of it by doing a BFT and then using the pascals triangle find the cells in each column of grid and then sum it, IS there any way to do it ??
There is a stack class which does push & pop in constant time. Introduce another function called min() which returns min element in the stack.
You have 1 white & 1 black container. White container contains 3 white balls and black container contains 4 black & 1 white ball. You remove one ball from black container and put it in white container. Now when you pick one ball from white container, what is the probability that it's a white ball.
Given a list of n integers?(negative and positive), not sorted and duplicates allowed, you have to output the triplets which sum upto 0.
Write an algorithm to find k numbers from a "stream" of numbers such that every number should have the same probability of getting selected.
Wat datastructure is used to store a more than 50digits number and to perform factorial
How to merge two trees with less time complexity.
how do you find the shortest distance (find a formula) for two points on the opposite vertices of a cube (shortest distance is actually sqrt(3) but can't cut through interior, must go along surface of cube)
8 ball question with a 9 ball variation. don't know if ninth ball is lighter or heavier (max 3 weighings).
There is very long array of ints, and you are given pointer to base addr of this array.. each int is 16bit representation... you need to return the pointer to tht "bit" inside array where longest sequence of "1"s start
how would you create the index for a book
3 ants are on different vertices of an equilateral triangle and can walk along the edges to any other vertex. what's the probability that any 2 of them will collide
Write test case for sorting an interger array.This is a simple sort program.
Print the path from root to a particular node given as input in a binary tree in the sequential order.
(need not be BST or balanced).
Find closest ancestor of two nodes in a binary tree.
why amazon?
Given a large file containing records(name,variable lenght address).Records are already sorted in alphabetical order.Give a DS to implement efficient adding /Deleting /Searching of the records.Suggested Trie .Gave 15min time to implement it
Given n two dimensional cartesian coordinates. How do you find if any three points are collinear. (i.e they all lie on the same line). I know the solutions for O(n^2) and O(n^3). Can you do it in O(nlogn)?
What data structure you will use to design a Dictionary of words. Each word have a description. Then tell what will be the a word lookup BigO.
int IsAnagram(char* str1, char* str2)int CutNPaste(char* str, int start, int stop, int destination)Write a program to print out the power set of a set.
Write a function to validate a SuDoKu board.
There is an array of size 'n' in which first 'a' elements are sorted in either ascending/descending order . The remaining elements 'n-a' elements are again sorted in ascending/descending. Find the index of the point of inflexion.If both parts are sorted in the same way return -1.
What is the difference between a process and a thread?
What is a CSS selector?
There is a large XML file, it has billions of sub nodes, grandparent nodes. Write an algorithm to find a node in the XML file.
What is normalization?
What is outer join?
Given 5 classess Person, Head, Body, Arm, Leg, how will you relate all the 4 classes in a object oriented way?
What is the visitor pattern?
Difference between Facade and Adapter Pattern?
Whats the difference between an interface and a abstract class?
What is polymorphism?
Given an array 1, 2, 3 ,4,4,4, 5,..,15,..,15,..,15...,..,15,....
How will you find the largest integer? Determine Complexity, how will you improve the complexity?
Algorithm for matrix multiplication two sparse matrix ( many 0s, a non-zero integer in a few places). The matrix is N X N. N is a very large number.
Algorithm for Depth first traversal of a TREE. How will you modify the same for a breadth first traversal?
What is a topological sort?
main()
{
char *s=f();
printf("\n String is %s\n",s);
}
char * f()
{
char b[10];
strcpy(b,"TEST");
return b;
}
What is the output of printf statement?
Why will printf prints junk values?
char ch[]="ab";
char *ch = "cd";
what is the difference between the above two statements?
What happens when I reassign some other values to above variables?
Find the two nodes in Binary Tree which has longest distance between them.
eg,
A
B C
D E
F G
I
should return B & I
Given a random number generator function rand(N) which generated numbers from 1 to N randomly. Give an optimized algorithm which when calls rand(N) generates all numbers from 1 to N uniquely.
Given a 2 dimensional plane in which there are n points. Give an algorithm to generate the equation of a line that divides the plane such that there are n/2 points on one side and n/2 points on the other.
Given an infinite array in which first N elements exists in sorted order. Given a number X, find the index where it exists. Give O(n) and O(lg(n)) approach.
How to find the missing K elements out of the unsorted natural N elements in an integer array.
Time complexity has to be O(n), with 3 extra variables of Space.
One suggestion was to do it in-place in the array.
Is there exists an in place countsort kind of method?
Input : Two sorted arrays, elements of both sorted in decreasing order : A and B.
Output : A matrix C with (a,b,sum) such that aEA, bEB, sum = a+b and in decreasing value of sum.
Complexity required : O(n)
Write a program to convert infix expression to postfix expression
Write a program to find the mirror image of a n-ary tree
given a structure,
struct {int a, float b, char c } x,y;
what are the 4 ways to copy contents of x into y?
Print a matrix spirally
Given ticker value for a stock, for next n days, given what is the max profit that you can make ?
Eg - the max profit you can make is buy at time t1 @ 5 and sell @ t2 when stock was 12, to get max Profit of 7 dollars.
time - Stock Price
t0 - 10
t1 - 5
t2 - 12
t3 - 7
t4 - 12
Also - you can only trade once i.e you can buy and sell only 1 time.
Given a binary tree , find out if the tree can be folded or not ?
Eg : tree (a) can be folded, but (b) cannot be folded
(a)
10(Root)
7(L) 15(R)
9(R) 11(L)(b)
10(Root)
7(L) 15(R)
5(L) 11(L)
Reverse an array of char in place.
Find the first unique number in an array of char.
Find the largest palindrome in a given string.
Two strings are given.How will you check if one is circularly equivalent to other string or not.
e.g. "abcd" is circularly equivalent to "bcda"
In an array there is one element which repeats more than n/2 times...find the number in 0(n) time and 0(1) space
Differentiate between arraylist in java and linked list.
Complexities for searching and insertion.
Given any Binary tree find lowest common ancestor.
Note: Binary tree , not BST
Given 2 linked list find the node where they intersect?
eg: LL1- 1-3-5-7-9-10-11-12-13
LL2- 2-4-6-8-10-11-12-13
they they intersect at 10
Given two n-ary trees T1 and T2. Write a program to check if T1 has T2 in it.
Consider 2 integer Arrays A and B. The elements in both arrays are arranged in ascending order. One of the arrays has exact sufficient space at the end to accommodate the other. Write a function to merge both arrays in ascending order and place it in the largest array.
Consider a right angled Triangle ABC, right angled at B. Lenght of side A (side opposite to angle A)is given. Write a function to find the lengths of side B and side C. The function should take the inputs ( Length of side A and one acute angle either B or C in radians).
1. Write all test cases.
2. Avoid division by zero.
3. Give different ways to implement cosine and sine functions. which one is best and why.
There are 10 Apple trees. A Farmer has placed these trees in 5 rows of 4 each... Can you tell me how to do it???
Write a function void DrawRectangle(char *Screen, int x1, int y1, int x2, int y2). Height and width of the monitor is known. To set a pixel, you need to set that particular bit of the screen.
Given two arrays A [n] and B[m], find the smallest window in A that contains all the elements of B.
Generate all the numbers whose factors are 2,3 and 5. How would you find nth number .
An array of integers of size n-1, all the elements are form [1,n]. Find the missing number. You can read only one bit in one operation, ie, to read A[i], you need to perform log(A[i]) operations.
Find median of two sorted arrays.
You are given a function char* getword(int index) and a sorted dictionary of unknown size. How would you find a word in the dictionary. The same question was asked in telephonic round as well.
When and where would you use the following data structures within the context of a virtual world? (array, linked list, hash table, binary tree).
char * copy(char *p)
{
char buf[1000] = {0};
//copy algo[I skipped code here]
return buf;
}
what is bug in this code? correct it.
Remove intersections of two single linked list and make one linked list. operations should be recursive.
Merge two sorted singly linked lists into one without using extra space and the duplicates should remian in the final list.
I was asked a question to get all the numbers from a file with a number per line.
I used streams and stored them in a vector.
However he told me that using a vector wastes space. How do you optimise . I told him I would use a linked list.
But he said he wanted to use a vector construct.
Write a function which takes x as a parameter and prints f(x)given that
f(0)=1;
f(1)=0;
f(x+2)=F(x)-f(x-1);
I wrote both the iterative and recursive versions.
the interviewer then modified the question
In the recursive version, print all the numbers in the series till the input parameter
Find out the first non duplicate character in a string.
eg: "nasa" output: 'n'
I have given a solution using hashmap.
Its o[n]+ o[n] performance. ( constructing hashmap + traversing the string )
He wanted solution with just o[n] which I was not able to write there.
Round-3-Qn-2)
- You are given two 4 digits prime numbers N1 and N2,
- You can change only one digit of N1 at a time.
- Resultant of changing a digit of N1 should also be a prime number.
How many number of digit changes (minimum) are required to convert N1 to N2?
Example:
Assume (8785, 8787, 8887, 9887, 9897) are prime numbers.
Lets say N1=8785 and N2 = 9897 then
change-1: 8785 => 8787
change-2: 8787 => 8887
change-3: 8887 => 9887
change-4: 9887 => 9897
So 4 digit changes are require to convert N1 to N2.
Round-3-Qn-1) It was repeated one. they asked the same round-1-Qn-1 question.
At starting of round-3, I noticed that interviewer has answer sheet of all my previous rounds and so i thought she is looking for some other alternatives than what i gave in round-1.
So i took 5 minutes to think of better solution but gave the same solution as i could not find any other better solution.
I made a big mistake by answering this question without saying "it was already asked in round-1". Because she assumed "i am cheating them.."... like that.
Thoguh i answered all the questions and performed well in previous rounds, it was the major reason for my elimination :(
Round-2-Qn-2) Implement a data structure such that it provides push(), pop() and GetMax() operations and running time of all operations should be constant O(1).
Note: GetMax need not remove the max from the data structure.
Round-2-Qn-1) Given a linked list L, we need to make a clone L'.
Note: a) Each node in the given list has an additional link called random that can point to any node (can also be null)
b) we need to make a clone of the list without using any additional space (need to allocate memory only for new nodes 1', 2', 3',...)
c) complexity should be O(n)
-->------
| |
L = 1-->2-->3-->4-->NULL
| | ^ |
|___|___| |
| |___| |
|<-----------
1->next = 2 1->random = 3
2->next = 3 2->random = 3
3->next = 4 3->random = NULL
4->next = NULL 4->random = 1
In L', the nodes should be
1'->next = 2' 1'->random = 3'
2'->next = 3' 2'->random = 3'
3'->next = 4' 3'->random = NULL
4'->next = NULL 4'->random = 1'Round-1-Qn-2) Given a binary tree, we need to create a matrix.
Example:
A
/ \
B C
/ \ / \
D E F G
|A|B|C|D|E|F|G|
------------------
A|
B|1 (B is child of A)
C|1 (C is child of A)
D|1 1 (D is child of A & B)
E|1 1 (E is child of A & B)
F|1 1 (F is child of A & C)
G|1 1 (G is child of A & C)Round-1-Qn-1) Find vertical sum of given binary tree.
Example:
1
/ \
2 3
/ \ / \
4 5 6 7The tree has 5 vertical lines
Vertical-1: nodes-4 => vertical sum is 4
Vertical-2: nodes-2 => vertical sum is 2
Vertical-3: nodes-1,5,6 => vertical sum is 1+5+6 = 12
Vertical-4: nodes-3 => vertical sum is 3
Vertical-5: nodes-7 => vertical sum is 7We need to output: 4 2 12 3 7
Written-Qn-3) Given a binary tree and a number N, check is there any path exists in the tree such sum of the nodes in the path equals to N.
bool isPathExists(Node *root, int N)
Note: We can assume that node contains only positive integers
Example:
1
/ \
2 3
/ \ / \
4 5 6 7if N = 8, return TRUE
if N = 9, return FALSE
Written-Qn-2) Write complete working code (only the function) to traverse a binary tree in ZigZag order
void printTree(Node *root)
Example:
1
/ \
2 3
/ \ / \
4 5 6 7O/P: 1 3 2 4 5 6 7
Written-Qn-1) Write complete working code (only the function) to check whether the given char sequence is valid.
bool isValid(char *str)
Example:
I/P: ()()().... O/P: Valid.
I/P: ())()(.... O/P: Invalid.
* We can assume that the input will have only squence of '(' and ')' chars.
Testing...Testing....
Tab Tab
Space Space
Space
Space
TabPlease delete this Qn
Given an array with 100 balls (each ball is to be imagined as an element in the array). 99 are of same weight only 1 is not. Identify the ball.
Use the given scale function:
int scale(array_name, start_index, mid_index, end_index)
returns: -1 if the left portion is heavier
1 if the right portion is heavier
0 if both left and right portions are equal.
assumptions: left portion: array[start] to array[mid]
right portion: array[mid+1] to array[end]
0,1
2 - ABC
3- DEF
4- GHI
5-JKL
6-MNO
7- PQR
8- STU
9- VWXYZ
Each number represents the set of variables and When we input a number . it should be replaced by all possible string values corresponding. eg : if we enter 27190000.
It should output.
APV
APW
APX
APY
APZ
In a company , there are three categories.A,B,C.
They want to give an increment.So if category C gets N% as increment. category B gets 2N% as increment and category A gets 3N% as increment.But the increment should be atleast 1% and The total updated salary should not exceed $50,000.
Print the increment and the total updated salary for a particular employee.
Assume all the required variables.
There is a security keypad at the entrance of a building. It has 9 numbers 1 - 9 in a 3x3 matrix format.
1 2 3
4 5 6
7 8 9
The security has decided to allow one digit error for a person but that digit should be horizontal or vertical. Example: for 5 the user is allowed to enter 2, 4, 6, 8 or for 4 the user is allowed to enter 1, 5, 7. IF the security code to enter is 1478 and if the user enters 1178 he should be allowed. Write a function to take security code from the user and print out if he should be allowed or not
For a given string replace all instances of ‘a’ with ‘one’. Note that ‘a’ shd be replaced only when it is a single character n not as part of another word.
Take the user gives a set of numbers as input.Stop taking the input when he enters 0. Display the maximum odd integer and minimum even integer.See that the user inputs correct values as input.
Given a binary tree print the nodes in this order:
all the left most nodes from top to bottom, then all the leaves, then all the right most nodes from bottom to top, then the root. like
10
5 15
3 2 12 17you would print 5 3 2 12 17 15 10
You have been asked to deploy a number of robotic domestic helpers (RDH) into a large room to remotely clean it as they move around it. This room is currently rectangular in shape and must be navigated by the RDH’s in order to successfully clean the room.
A RDH position and location is represented by a combination of x and y co-ordinates and a letter representing one of the four cardinal compass points. The room is divided up into a grid to simplify navigation. An example position might be 0, 0, N, which means the RDH is in the bottom left corner and facing North.
In order to control a RDH the operator sends a simple string of letters. The possible letters are 'L', 'R' and 'M'. 'L' and 'R' makes the robot spin 90 degrees left or right respectively, without moving from its current spot. 'M' means move forward one grid point, and maintain the same heading.
Assume that the square directly North from (x, y) is (x, y+1).
INPUT:
The first line of input is the upper-right coordinates of the arena, the lower-left coordinates are assumed to be 0,0.
The rest of the input is information pertaining to the RDH’s that have been deployed. Each RDH has two lines of input. The first line gives the RDH’s initial deployed position, and the second line is a series of instructions telling the RDH how to navigate around the room.
The position is made up of two integers and a letter separated by spaces, corresponding to the x and y co-ordinates and the RDH’s orientation.
Each RDH will be finished sequentially, which means that the second RDH won't start to move until the first one has finished moving.
OUTPUT
The output for each RDH should be its final co-ordinates and heading.
INPUT AND OUTPUT
Test Input:
7 6
2 4 E
MMRMMRMRRM
3 4 N
LMLMLMLMM
Expected Output:
4 2 E
43e3 5 N
An rpc server is given which receives millions of requests a day. Each request i takes processing time Ti to get processed. We want to find the 65th percentile processing time (when processing times are sorted according to their values in increasing order) at any moment. We cannot store processing times of all the requests of the past as the number of requests is very large. And so the answer need not be exact 65th percentile, you can give some approximate answer i.e. processing time which will be around the exact 65th percentile number.
Hint: Its something to do how a histogram (i.e. an overview) is stored for a very large data without storing all of data.
Given a file that contain huge number of integers. You have to find out sum of K numbers who's sum is largest, find out the best way.
Given a sorted array of n integers that has been rotated left or right by k places, give an algorithm that searches and finds an element in the array in log n time.
Example Input: 8 9 0 1 2 4 5 6 (sorted array rotated right by 2 places)
how will you implement pow(a,b) without using multiplication or division operators. You can use only add/substract operators.
Am going for a interview @ vmware, bangalore centre? Is it worth applying for vmware? Howz HR and management in general?
write thread safe singleton class
stack pointer vs frame pointer
Given Numerator and Denominator. After division you might get a recurring decimal points float as the answer. You need to identify the recurring part?
For example 23.34563456 ...
return 3456
Suppose you are given an infinite series of strings, each at a certain position as follows:
1. a
2. b
3. c
4. d
..
26.z
27.aa
28.ab
..
52.az
given the nth number you need to identify the corresponding pattern string. For example if I give you 1 you need to return a or if given 27 u need to return aa.
Identify the first character in the string which is getting repeated.
For example acadc return a.
Hi, Can someone define and give examples for rotating an array clockwise, anticlockwise.
Also how to shift an array circularly?
There are 2 Persons A and B. A is given sum of 2 numbers (X+Y), while B is given Product of the same 2 numbers (X*Y).
Our purpose if to identify the two numbers.
We asked A "Do you know the numbers?" A answered NO. Then we asked B "Do you know the numbers?" B answered No. After that again we asked A now can you tell me the numbers A says YES and then B also says I can identify the number. Can you tell me what are those numbers?
There are infinite sets of strings given to you as follows:
a,b,c .. z,
aa,ab,ac ..az,
ba,bb,bc...bz,
ca,cb,cc ..cz,
....aaaa....bbbb........
Given a number return the String at that position. For example given 1 should return a, given 27 should return aa and so on.
thats the end of it... took around 53 minutes...I know it was a disaster.
Being good is not enough. you have to practise too.!!!
At this stage, the standard of questions has degraded. I know this is going to be a disaster !!
Q) Palindrome Algorithm
A) I wrote the algorithm, but made few mistakes like writing "if" conditions for null pointer exceptions. He made me point out that by asking me by giving a test case of null string. So again..practise well.
Q)Which data structure would you suggest for auto completion feature in text typing like an application in iPhone?
A) I have no clue, initially I told him I can use a Binary Tree but I could not convince him why I would use that. then I told Hash tables.
Q) What is the disadvantage in using Hash tables?
A) Memory I told him. I don't know if that is a wrong answer.
Q) Difference between LinkedList and ArrayList
A) I told this correctly. this is an easy one.
Q) OK. I have two large files (10 MB) each how do you compare them and remove common elements in a file.
A) I told him split the files into 1 MB each and do an intersection on them get the result in another file and concatenate them back. But he asked me what datastructure I would use.
I was bowled. (This is the result of lack of proper preparation!!)
Q)OK. Do you know any design patterns? If tell me about any one pattern?
Ans: 3 patterns in general: Creational, Structural, Behavioral
Q)what is behavioral pattern? give me an example.
A) I answered different objects working together towards a solution is behavioral design pattern. (Is it right? I think so)
Q) Can you give me an example
A) Model View Controller.
Then he gruelled me on MVC. I don't want to print all that here. So be aware before you answer which is actually difficult in an actual interview !
Q)OK. So which end do you want to work? Front end or back end?
Ans: I prefer server side (back end).
Why do you want to work for Amazon?
I answered I am interested in Web application development and Amazon is a great place to work with space for innovative thinking. What do you want to say? you think yourself.
After first phone interview, I observed that Amazon do not want people who just knows a book by its cover they are looking for people who knows each and every letter in the book !
So prepare well , don't hurry if you get an interview call, even if you are good, you may not do well unless you are prepared very well. Unfortunately, I am just one of those :(. All right see below the questions asked.
I would say Adobe hiring people are DUMB. They have pre determined soln in mind and they only expect same soln .. . They dont appreciate different thought level with same complexity soln.
So they want Soln learners and not Soln explorers and pattern finders.
Given a array 123456789
He would you rotate it like 7891234567
Do reverse string complete and then twice revert at pivot. O(N).
I gave another O(N) soln which is tricky .. . but interviewer (hiring manager) was like ek or O(N) soln hai wahe do .. .
There are N nuts and N bolts, all unique pairs od Nut and Bolt
You cant compare Nut with Nut.
You cant compare Bolt with Bolt
You CAN compare Nut with Bolt
Now how would you figure out matching pairs of nut and bolt from the given N nut and Bolt.
The basic soln is O(N^2). Give O(NlogN soln)
You are given four no 1,2,3,4. The score to start is zero.
There are two people. Each one has to choose one of 1,2,3,4 alternatively and add to score. The person who reaches the score value N (variable given as input) 1st will won.
What will be your strategy.
Puzzle, A square Island surrounded by bigger square, and in between there is infinite depth water. The distance between them is L. The wooden blocks of L are given.
The L length block can't be placed in between to cross it, as it will fall in water (just fitting).
How would you cross using these L length blocks.
Initialization list in C++ constructor
What is tiny URL. How would you implement it. I told hashing and defended it with reasons. But interviewer was not happy .. . I could not understand what he really expects .. .
Implement Mutex.
Implement fibannoci func for nth number. I told never use recursion in production code. Stack overflow can corrupt your system.
I am in a 100-story building. I have with me two glass balls. I know that if I throw the ball out of the window, it will not break if the floor number is less than X, and it will always breaks if the floor number is equal to or greater than X. Assuming that I can reuse the balls which don't break, find X in the minimum number of throws.
Effect of calling virtual function in C++ constructor
1) Find all permutations of a string.
2) Improve it so that the permutations are not repeated, Eg=> string is "aaaa"
Answer should be just aaaa once not 4! times.
Give a practical scenario and code scenario (please not Producer-Consumer) where Deadlock occurs. Full detailed discussion on deadlocks only.
What data structure to use to store all names in Sunnyvale - Hash table or Tree? When to use Hash table and when to use tree.
Given an array , delete all duplicates in it.
Two unsorted linked lists are given.
Find the union.
Eg: a) 1->9->9->5->7->8->9->7
b) 44->33->1->9->55
Result:
1->9->5->7->8->44->33->55
The elements in the result can be in any order
Given a very very long linked list with 'n' nodes.
Also given a positive integer 't'>1.
Delete every 't'th node. In the resultant linked list, again delete 't'th node. Repeat this till only t-1 nodes remains.
Find the node.
Eg:
Linked list : 10->20->30->40->50->60->70
n = 7
t = 3
Phase 1:
10->20->40->50->70
Phase-2:
10->20->50->70
Phase-3:
10->20->70
Phase-4:
10->20
Simple solution with many traversals is obvious.
Is there a solution with one traversal or O(n)?
b) Similar for circular linked list.
Keep deleting 't'th node till 1 node remains.
Note here not till 't-1' nodes but till 1 node remains.
sort an array of 0,1 and 2.
Given two arrays : arrivals and departrues array
arrivals[i] -- arrival time of flight i
departures[i] -- departure time of flight i
when a flight arrives at the airport, you have to provide a stair case to the flight
and when it leaves you can take it back.
find the min number of stair cases required.
Given a Hash -
my %hash = (
ABC => [123,456,789],
PQR => 345,
XYZ => 567,
LMN => {
abc => 0,
pqr => 1,
lmn => 2,
xyz => {
A => 0,
B => 1,
c => [ {1 => 'ONE', 2 => 'TWO',},
{ONE => 1, TWO => 2,},
{Number => 'Decimals'},
{Words => 'Alphas'},
'Sample'
]
}
},
OPQ => 'WORD'
);Write a generic function to find value of key input by user.
e.g. In above example if key input by user is 'Words' then value found by search function should be 'Alphas'
Write Search($hashRef,$key) function where, hash could be of any type/level such as -
Hash of Hash of Hash of Hash
Hash of Array of Hash.
etc. etc.
Integer has been represented in linked list. Eg. 7541 has been represented as 7->5->4->1 with 4 nodes each having a digit. Given 2 such linked lists, you need to compute the sum of them.
There are n petrol bunks arranged in circle. Each bunk is separated from the rest by a certain distance. You choose some mode of travel which needs 1litre of petrol to cover 1km distance. You can't infinitely draw any amount of petrol from each bunk as each bunk has some limited petrol only. But you know that the sum of litres of petrol in all the bunks is equal to the distance to be covered.
ie let P1, P2, ... Pn be n bunks arranged circularly. d1 is distance between p1 and p2, d2 is distance between p2 and p3. dn is distance between pn and p1.Now find out the bunk from where the travel can be started such that your mode of travel never runs out of fuel.
Difference between AVL trees and Red black trees.
Find the intersection of two linked lists.
Optimum space and time
Given a directory path find the most optimum traversal.
eg: \a\c\..\d => \a\d
\a\b\c\..\..\d\.. => \a
etc
Merging 2 binary trees.
Given a binary tree, and 3 nodes x,y,z write a function which returns true if y lies in the path between x and z and false otherwise.
Given a 2-D matrix sorted by row and column, You need to search for an element in O(n) time.
How will you reverse a singly linked list.
Various locks- Reader-WRiter lock, RWGuard locks, prod-consumer lock process, couple of TCP/IP and UDP questions. Message in TCP always appear in the order sent.
FIX protocol, messages, architecture and how the whole process is carried out.
If you have included FIX in your resume then definately refer to the pdf here:
ksvali.com/2009/02/fix-protocol-videos-on-youtube-finally/
Handler-body idiom design.
We chatted for an hour. I cracked most of it but I got too hacky while suggesting solutions. He said I was sneaky! :D But made him understand that I wanted to crack the questions first and then would go for a better design/implelementation.
Producer-Consumer template implementation, including minute details. Instead of including the While(Condition){ wait on a RW conditon}, I included the If(condition) like a dumbass :(
But he was very good and understanding.
Write code to return the numbers of almost prime numbers in a given range. Remember an almost prime number is a number one degree off prime - basically a non-prime number divided by a prime number that equals a prime number.
example: 4/2 = 2 or 26/13 = 2 both numbers are almost prime numbers
given in question: the first 25 prime numbers are - 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97.
write code to return the shape with the largest area in a collection of shapes. the shape can be a square, circle ,or rectangle. The collection can hold any type of these shapes
write a method to return first non-repeated character in a string. example: String = "total" then method returns char = 'o'. then explain why you choose your algorithm.
Write a method to find the Fibonacci number of any given number. do it in any OOP language.
basically about my skill set and why I was looking for a job change.
Virtual constructors - using Clone and Exemplars. Minute details and implementations.
Shared_ptr internal implementation, where is the counter placed, it's template definition, etc
Given a Hash -
my %hash = (
ABC => [123,456,789],
PQR => 345,
XYZ => 567,
LMN => {
abc => 0,
pqr => 1,
lmn => 2,
xyz => {
A => 0,
B => 1,
c => [ {1 => 'ONE', 2 => 'TWO',},
{ONE => 1, TWO => 2,},
{Number => 'Decimals'},
{Words => 'Alphas'},
'Abhishek'
]
}
},
OPQ => 'WORD'
);Write a generic function to find value of key input by user.
e.g. In above example if key input by user is 'Words' then value found by search function should be 'Alphas'
Write Search($hashRef,$key) function where, hash could be of any type/level such as -
Hash of Hash of Hash of Hash
Hash of Array of Hash.
etc. etc.
use following code to return boolean value based on match
return my_hash.contains(strEnteredVal);
Given is any kind of hash reference simulate the dumper to print the hash.
Given an m-ary tree, need to implement two functions lock and unlock on a node n. You can lock a node if none of the nodes in its subtree is locked and none of its ancestors are locked. Unlocking a node should release the lock. Suggest a good data structure for solving this. And implement the lock and unlock functions in O(log n) time.
This Question is asked in a written test of microsoft in Bangalore today.
given two sorted linked list.
Write a recursive code to find the intersection of two list.
the resulted list must be in sorted order.
all unused node should be deleted using "free()".
method Signature was given..
Node *SortedIntersection(Node *l1, Node *l2)
write a method that is used to test the input string arrays for equality.
The input arrays need not be ordered in any way and may contain duplicates.
The order of the elements in the arrays and duplicates are ignored.
For example the following two arrays will be considered equal:
{"a","b","ab"} is equal to {"a","b","ab","ab"}
The following arrays are not equal:
{"a","b"} is not equal to {"a","ab"}
this is your signature:
public static boolean allStringSetsIdentical(String[][]sets){
tell the o/p of:
int main(){
int n = 255, i;
char *p = (char *)&n;
for(i = 0; i < sizeof(int); i++)
cout<<*(int *)p<<"\n";
return 0;
}
suppose we dynamically allocate the memory using malloc eg char *p=(char *)malloc(8*sizeof(char)) and then we deallocate it later using free command eg free(p) then how does free know about the size of memory to be deallocated i.e. how does it frees just the amount of memory allocated to pointer p....
Imagine you have a hard disk with blocks of memory 1..n. Files can be stored on one or more of these blocks. If a file spans more than one block, you can know the next block by querying the current block. Also you can query block with Node.isEmpty() method to know if it has any data. The system has a table which has a list of the files and the first node of each file. But that table has been corrupted, reconstruct that table. The names of the files are immaterial and you can get the index as well as the name of the nextblock when you query for Node.NextBlock()
Say you have a binary tree which looks like this
A
/ \
B C
/ \ / \
D E F G
/ /
H IAssume A is level 1. So here you can see that the width at level 3 = 4, which is the max width of the tree.
So given a binary tree, find the max width of the tree.This is your function:
public int findWidth(Node root)
and public Node{
String val;
Node getLeft();
Node getRight();
}Given a binary search tree and all the elements of the tree are negated, re organize the tree such that the tree is a BST
There are two robot standing on two ends of a line, somewhere on the line there is a point and I need to make both robot reach that point. Same program is running in both robots. Only instruction allowed is : Move Left, Move Right, Am I on point. Tell how both the robots will meet.
how to know if OS stack is growing up or down in plain C.
Lots of stuff about linux scheduler.
Input is a NxN matrix which contains only 0's and 1's. The condition is no 1 will occur in a row after 0. Find the index of the row which contains maximum number of zeros.
Example: lets say 5x5 matrix
1 0 0 0 0
1 1 0 0 0
1 1 1 1 1
0 0 0 0 0
1 1 1 0 0
For this input answer is 4th row.
solution should have time complexity less than N^2
Given a linked list of numbers. Swap every 2 adjacent links.
For eg if a linked list given to you is- a->b->c->d->e->f
O/p expected- b->a->d->c->f->e
Every 2 alternate links have to be swapped. Pls note that values stored in the link list have to remain at their previous locations only. Values are not to be swapped. Only links are to be swapped.
You have been given a linked list of numbers. The size is not known. You need to find out if the number stored in the list is a palindrome in the best possible optimized manner.
Given a furniture which can be made of wood or metal and can be a chair or a table and a type of stress like fire and water, simulate a system or give me a design to handle all this.
Furniture is a class and class chair and table extend it. Test is a class which takes the object furniture and type of stress and return bool type. He then asked me what if i keep increasing the type of stress. So my approach for this was to have a class or function dedicated for each type of stress and just pass the furniture object. There was a lot of discussion on the same lines.
What are prepared statements? what is indexing and also what is sql injection and how do you prevent it.
Given a point p and a list of points, find k point closest to the point.
I told him the naive method keeping track of the min distance and already returned points we could find next closest point in every loop. He asked me if i could improvise it using some sort of data structures then i told him range queries.
Given an array of integers, find two integers whose sum is x? He asked me to give him different approaches.
1. Naive method using two loops. ie. O(n2).
2. Uisng sorting as a preprocessing step and binary search. ie. O(nlogn).
3. Hashing. O(n).
He also asked me the end cases that should be handled. In hashing method negative numbers cannot be handled.
The interviewer was looking for all the approaches.
This Was the toughest and last question
0,1
2 - ABC
3- DEF
4- GHI
5-JKL
6-MNO
7- PQR
8- STU
9- VWXYZ
Each number represents the set of variables and When we input a number . it should be replaced by all possible string values corresponding. eg : if we enter 27190000.
It should output.
APV
APW
APX
APY
APZ
...........
In a company , there are three categories.A,B,C.
They want to give an increment.So if category C gets N% as increment. category B gets 2N% as increment and category A gets 3N% as increment.But the increment should be atleast 1% and The total updated salary should not exceed $50,000.
Print the increment and the total updated salary for a particular employee.
Assume all the required variables.
At a geeks goodies store.. every thing is either one dollar or less. and they accept only 10 dollars or less than 10 as denominations.So make a function that takes in the cost and payment as input and that out puts the change.
The denominations are namely 1c,5c,10c,25c,$1,$5,$10
Take string as an input from the user.After taking. consider A ,a ,e,E,i,I,o,O,u,U, -- if these letters appear in the string.. then replace them with A^ ,a^,e^,E^,i^,I^,o^,O^,u^,U^. leave the first three eligible letters from the starting of the string.---
example --- greateribblizing.
converts to greateri^bbli^zi^ng.
Take the user gives a set of numbers as input.Stop taking the input when he enters 0. Display the maximum odd integer and minimum even integer.See that the user inputs correct values as input.
Design a game called "Checkers"
Given an array with random numbers, all the numbers occur even number of times EXCEPT one number which occurs odd number of times. Find that number.
In the given string remove a given char and print the new string without.
Example:- String is "This is a boy" chars to be removed is "is" .The final string will be "Th a boy"
An executive walks into your office and says Bing is not doing great for a specific category of queries. What would you do to improve or get rid of the problem ? (Interested in analysis of logs to understand the real problem, various solutions (short term/long term), what would get rolled up for visibility from higher executives (new UI etc)
Do you know about the recommendation engine built/used by Amazon.com ? How would you build one ? Now use what you know to build a relevancy engine for Bing Search.
You have access to one month of query logs, website logs what inferences can you draw about query relevance for Bing search ?
Design a spell checker - starting from APIs, way it is to be used as a product or service,components included, how to be integrated with existing word processors, who should be target users, Programming concepts that should be used to build, how it can be updated later, newer versions to take care bla bla bla.. like this
general - asked about my passion and what i really want to do in life as a professional
design - design a system which can give a good offline browser experience, or manage discontinuity in internet connectivity, means if a person is browsing some site, and even if there are fluctuations in his connectivity to this site or internet yet browser should have some system which will give a smooth user experience. I tried with some kind of pattern recognition in the users activity and depending on that pre-downloading the next probable page and making it available.
algorithm - given binary tree, check if it has any 2 leaf nodes which differ by more than 1 level (write code for this)
Designing a middle ware, which is connecting a user interface and back end servers. Will have to consider all the aspects starting from load balancing, security, API s to be built, data structures to be used etc etc
write a code for which input is a string and set of characters acting as delimiters. Cut the given string where ever delimiters occur and return all the set of sub strings. For eg: given string abbcdeffghujsb and delimiter set:c,g,j
then output should be: abb, deff, u, sb
Mathematical - logically explain the summation of a geometric series starting from 1/2 and growing by 1/2 each time {1/2 + 1/4 + 1/8 + ..}
puzzle - 2 trains traveling in opposite direction, bird starts from one and reaches other and flies back and forth like this till train collide. Find the time taken to collide, total distance traveled by the bird, and no. of times bird makes a U turn.
How to use "FILO stack" to implement a "FIFO queue"?
Hint: try to use two stacks
main() {
unsigned int a = 10;
int b = -19;
puts((a+b)>0? "Positive":"Negative");
}The output answer is "Positive"
Does anyone know why the sum will typecast to "unsigned int"??
find out all the elements in a sorted integer array whose value is equal to index of the array.
O(logn) solution is expected.
Now it is time for pay back.
This site has been an awesome tutor for me, long live CareerCup...!
I am describing the entire Program Manager interview that went on for Microsoft. Click on the "Full Interview" link to see all the questions.
After ppt and stuff we had one round of written test:
4 questions and sufficient time i guess.
one on following a C code and writing the output, another on writing test cases for fopen() function, third one on designing and coding an algorithm to find the first common node when two linked list merge and lastly a design problem to design a tv remote for children under age 6
You can find answers for all the above in this site.
7 out of 42 were shortlisted for interviews.
Given a array of random integers, sort the odd elements in descending order and even numbers in ascending order.
e.g. for i/p (1,4,5,2,3,6,7)
O/p = (7,5,3,1,2,4,6)
Optimize for time complexity.
find a cycle in a directed graph
Randomize a given array, discuss optimizations
What is pure virtual function ?
Implement binary search.
Number of binary 1's in an integer n umber.
Given a unix path Eg: a/b/../c
Write a C code to fetch the output as
a/c.
i.e a is the root directory . cd d gives a/b. and cd.. goes to parent directory a. and again cd c . so the output shld be a/c
given n 1*1 squares , find the rectangle(x,y) that fits the n squares with the following conditions
1. the area of the rectangle x*y = n or n+1 or n+2
2. |x-y| is minimum
example: n = 7, then possible areas is 7,8,9 and x,y can be (1,7) (2,4) (3,3) answer is 3,3
given n write a function to print x,y
there are 2 types of bricks 1*2 and 1*3, in how many ways can u build a wall of length n and height 1.
i.e for wall of length 7 and height 1
ans - 223, 232, 322
for wall of size 8
ans - 2222, 233, 323, 332
given n write a function to print all possiblilies
given a number n say 234 print as follows: 2,3,4
What is cache ? How it is used and mapped the physical address cache and virtual address cache ?
User application will block on IOCTL, in kernel untill interrupt arrives this IOCTL will be blocked. When interrupt comes IOCTL should retun. Desing this mechanism.
What is IOCTL, how it is used in user and kernel driver code ?
What is difference between named pipes and unnamed pipes ?
What is difference between wake_up ( ) and wake_up_interruptible ( ) APIs in linux kernel ?
When should should use which one, how it should be decided ?
What is difference between sleep_on ( ) and interruptible_sleep_on ( ) APIs in linux kernel ?
When should should use which one, how it should be decided ?
Count number of digits after the decimal point
Ex 7.563 output is 3.
Ex 7.500023 output is 6.
Given two sorted postive integer arrays A(n) and B(n) (W.L.O.G, let's
say they are decreasingly sorted), we define a set S = {(a,b) | a \in
A
and b \in B}. Obviously there are n^2 elements in S. The value of such
a pair is defined as Val(a,b) = a + b. Now we want to get the n pairs
from S with largest values.
You have a array of random numbers and you are given a number k. Find the 2 elements in the array which sum up to k.
e.g: If my array is {2,5,3,1,8,7,5,4} and k=6.
Then 2 numbers that sum up to 6 are 5 and 1.
you are given 80 balls and out of which only 1 has more weight than other 79. also, you are given weighing machine which can weigh any number of balls of 2 sets( 40 40 or 25 25 etc) at one time.
find the minimum number of steps required to find the ball of more weight than others. (i tried it came out to be 5 steps atleast, but he wanted more efficient solution )
how will you test a calculator?
how to find a the ph no. of a candidate which is not mentioned in the resume?
implement a program for weighted numbers. Design a test case for the same.
You are given 2 blocks of data. implement a function which would copy the data contained in block 1 to block 2.
hint:memmove, memcpy wont take care of duplicates.
You are given a matrix of size M rows and N columns. A is the first element i.e. mat[i][j] where i=j=0, and B is the end point i.e. i=M and j=N. There is a robot at A and it can only move one step right or go down one step. There are walls in the matrix denoted by X. The robot cant make his move when it encounters a wall on right or on its way down. Find the number of paths from starting point A to the end point of the matrix B for the robot.
hint:recursion with condition checking for the end point and the wall.
What is the use of overriding in OOP
Given a large file, having N (N is very large) positive integers, how will you find a pair of numbers that add up to x (eg. 100). What data structure will you use and give appropriate Algo/code. It should be efficient in time and space.
If have given a word(string/char array) and flat file containing list of all existing "real english words", find all possible real english words that made of using "ALL" characters of input word
Implement a routine “void CopyMemory(void *pvSrc, void *pvDst, unsigned long ulLen)” to copy memory from one place to another.
We can implement in any language C++,C#,java
Remove tail recursion from recursive inorder traversal in a BST. Also perform an iterative in order traversal.
Without using /,% and * operators. write a function to divide a number by 3. itoa() function is available.
Question in speech recognition. Design and implement an algorithm to match formants on spectrograms, subject to non-linear transformation of time and frequency.
Design a compact data structure representation of a graph.
Given a matrix of integers sorted along each row and each column, implement a rapid search algorithm.
Reverse a linked list with O(1) memory, and O(n) time.
Design and implement the backend for the game 'Battleship' for 2 players. Discuss scalability, generalizations etc. Design Patterns based question.
Given an image represented by an MxN matrix where each pixel in the image is 4 bytes write a method to rotate the image by 90 degrees Can you do this in
Write code to copy a graph.
In the attached Excel file there is a list of 500 posts taken from an online community. Write a program that finds the 100 most popular one, two, three, and four-word phrases when the “Run!” button is clicked. Please, take into account the following:
1. All words in a phrase must belong to the same sentence in the post.
2. The following characters must be used to separate one sentence from another within the same post:
1. . (Period)
2. ! (Exclamation mark)
3. ? (Question mark)
4. ; (Semicolon)
5. : (Colon)
6. Line feed
7. Carriage return
3. At least one word in any phrase must not be from the “Excluded Word List.”
4. The program must return the phrases ranked in descending order according their frequency.
5. Execution time is very important, so the program should run as fast as possible (run time will be taken into consideration when grading the assignment).
barring the first 3 vowels in a string , convert all vowels to a e i o u ( with a caveat , something like special vowels in french and other european languages) . at the same time not more than 4 vowels from the last shud be changed.
Implement a semaphore using a mutex
how is a system call executed.. when the API resides in the user space how are u still able to execute kernel code.
what all errors is possible if u write past the array bounds
Explain the difference between Memory mapped I/O and DMA
what does fork do, can the child process use the fd's immediately
You have experience in telecom domain. Why do you want to work in Bloomberg?
Write code to implement the 'wc -l' feature..
what is new in C++, and operator, function, functor?
what will be size of class and size of object of class.
class A{
int *p;
static int a; }
exception handling. can we throw different type of object in re throw ?
in singleton class how will delete the obj ?
what happens if I throw exception from destructor. can I throw exception from construtor and destructor ?
in unix one task/process is stuck. How will debug it ?
is template class compilation static or dynamic binding ?
there is template class with syntax errors and in main prog there is nothing.
will it throw compile errors ?
when you will provide overloaded new operator. give example
when you will provide your own copy constructor, assignment operator. give example.
Given a binary search tree and N. Write code to find out the Nth node from the last. [ Here last with respect to the inorder traversal.]
write a function which takes a number as input and returns it next number. Condition: the next and given number should have equal number of 1's in its binary format.
Example: 5 - 101 its next number 6-110. both have two 1's.
Input:
Given a sorted array (ex. {1,2,3,4,5,6,7,8}). A random number from the array is taken and put the left side array to right side and left side array to right side.
in the example; if 6 is randomly taken, the array will become like {7,8,6,1,2,3,4,5}
Question:
Given the above mangled array, write a searching algorithm to find a number present or not. That algo should not be of O(n) solution.
Prepare a presentation on a project that you believe is the most challenging project that you have undertaken , explain the concept , approach , algorithm .. this presentation lasted for 30 + mins. in which mainly the interviewee does the talking.
Epic is based a lot on luck than skill as in microsoft , amazon and bloomberg... since there would be an HR interview, and a programming test to be done on pen and paper , a quantative test which is simply high school math, a 2 min test on analytical skills , diagrams , series etc, and a test on basic concepts like variables , arrays ...(which is designed for people with non programming back ground).
All my rounds were flawless.. still got a reject.
Are you willing to relocate to madison?
What would prompt you to accept an offer from another company instead of epic
You have a stream of numbers of unknown length. When you hit a zero, the stream is terminated. Return the largest even number and the largest odd number.
You are supposed to write a code for a cashier such that , given the money paid by the customer and the cost of the product , if would display the number of 10 dollar notes, 5 dollar notes, 1 dollar notes...quarters ,dimes .. in decreasing order ( something like applying greedy approach).
If you have 50G of log file with timestamp messagetype and message body info find the logs that have message type "FATAL" logged between 3-5 pm
Given a set of points in a plane. Write a function to check if there exists a vertical line of symmetry in this plane.
Given a function that takes in an integer input and gives out an integer:
int func(int input);
This function is deterministic. It always gives the same output value for a given input. Say func(8) = 7 whenever it is called.
Now this function is called multiple times in a loop. This would generate a stream of integers [which are the outputs of that function for different inputs to the function]. He asked me what is the length of this loop ? When i said i didn't understand by what he meant, he said, give me the count of how many numbers are repeated and how many numbers are not repeated. He said there is very limited memory: you can store only a certain number of integers at a time, but not all of them.
Distinguish auto pointers and shared pointers. Write C++ to implement a shared pointer class.
Given an 32-bit integer X, swap the i-th and j-th bit.
A ship has x pirates, where the age of the jth pirate is a(subscript)j and the weight of the jth pirate is w(subscript)j. I was asked for a dyn. programming algorithm, which will find the oldest pirate whose weight is in between twenty-fifth and seventy-fifth %ile of all pirates. I was asked this during onsite interview.
Difference between a process & thread .If one thread gives a pointer to a variable in its stack to another thread will it be able to access it .Can 2 processes have a shared variable..or is it possible only b/w 2 threads.
Explain the different types of polymorphism in C++
u have an array A of unknown length L. The array contains numbers that are distinct and sorted ascendingly. The array is 1-indexed i.e. first element is got by A[1] and not A[0]. To help u, since L is not known, when a index out of bounds is used, then a special value of NOT_FOUND is returned.
the question is to find some positive integer n such that when used as the index, the result from the array is the n itself. i.e. A[n] = n.
how will you write constructor such that if will deallocates memory when there is exception.
exception handling. can we throw different type of object in re throw ?
what happens if I throw exception from destructor. can I throw exception from construtor and destructor ?
is template class compilation static or dynamic binding ?
there is template class with syntax errors and in main prog there is nothing.
will it throw compile errors ?
Given a two integer n and d. Print the value of n/d. When n/d may or may not have decimal digits. In case of numbers n=1 and d=3, n/d=0.3333333.... So when there is a repeating pattern the output should be 0.(3), In case of a n/d = 3.12454545454545.... the output should be 3.12(45), for n/d = 4.123982 the output should be 4.123982. Give a solution and write code for the same.
Differentiate between threads and processes
What are spin locks, are they better then mutex ?
What are virtual functions?
different between exec and fork. will parent process and child process
in deadlock if parent is using resource and child will also get same resource ?
what if parent contains two threads ? will child also get 2 threads ? how fork will be thread safe ?
Use only single variable to print the binary format of that number....just use single variable thats all....
For example if u read the value to variable N as 10 then through out the program use only variable 'N'..not use any more .....
Given N Points in a Plane find the sets of Collinear Points.Collinear points are 3 or more points on the same line.(2 points are trivially collinear).
why assembly versions improtant in c#.net
what is diffrence b/w fungtios &properties
Three boxes, one with apples, one with oranges, one with a mix of apples and oranges.
all the boxes are labeled incorrectly.
you can pick up just one fruit.
and tell which box has what fruit.
Write a Java program (which uses no external storage) that prints "Register Now !" for the first 30 days of its use. After the 30th day it should print "Free Trial Expired!"
where is volatile variables stored in memory layout ?
How to write on a specific location / address on a device driver or register ?
How to write a perticular value on real hardware register or hardware address in device driver programming ?
Write a program to find most 2 visited pages from big log file that contains list
of sessionId and PageId combination in each seperate line. File is big enough not to fit in memory.
It means find out pair of page that is bening visited most in same session(user).
design spice rack for blind
design a kitchen for blind
design deck of cards
What's the three types of memory allocated for C++ variables?
where is global variable (defined outside any function or class) allocated, heap or stack?
you have a class A, where you set ctor to be private, so a client can't call
"A a;"
to create obj on stack.
But someday another developer add a new ctor:
"A(int)"
and try to call "A a(1);" inside main(). So this will create a obj on stack. How do you prevent that?
Can an object be passed by value instead of reference as a parameter while overloading assignment operator ?
The parameter should be const or not ?
Difference between XML and HTTP.
What are features of optimum Java code.
Webservices: How would you test your web service, which language would you use to test the webservice.
Explain Abstract class, Inheritance
What is a StringBuffer and why do you use it?
What is Inheritance and Polymorphism
Why Rapleaf?
We’re excited that you’re interested in a position here at Rapleaf. Why are you interested in working at Rapleaf in particular? What about Rapleaf excites you? Please limit yourself to 1-2 paragraphs.
An Activity to Further Your Gambling Addiction
If you roll 5 standard six-sided dice, what’s the probability that you get at least two 4s?
Also: you were offered the following bet: we pay you $1003 if you roll at least two 4s but you have to pay Rapleaf $1003 if you don't. Would you take the bet? Why or why not?
Six Degrees of Turkey Bacon
You've always been intrigued with the "Six Degrees of Kevin Bacon" game (http://en.wikipedia.org/wiki/Six_Degrees_of_Kevin_Bacon). Now, let's say if two actors have been in the same movie we call them "friends" and if two actors have not been in the same movie, we say they are not "friends." Now choose any two actors at random -- we want to calculate the number of degrees of separation and the path between them. How do you go about this problem? Discuss ideas, trade-offs, algorithm ideas, and more.
The Max
Bubble sort is O(n) at best, O(n^2) at worst, and its memory usage is O(1) . Merge sort is always O(n log n), but its memory usage is O(n). Explain which algorithm you would use to implement a function that takes an array of integers and returns the max integer in the collection, assuming that the length of the array is less than 1002. What if the array length is greater than 1002?
what is polymorphism. example.
design deck of cards
diff between pointer and reference
given a number, 9th bit set or not?
Height of a BInary tree.
How would u create ADT for Hash map.
Which Data structure would u use to implement phone book of mobile
Which algorithm would u use to sort a very large file
Given a binary tree, wap to return a new tree which is mirror image of the given tree
Write test cases for a function which takes a citi name as string and returns the temperature ad double. returnFunc(String name)
Also give any suggestion for improving this API
In an array of integers find a pair of words which product equals to given number without using any extra space.
In a very large file find the 3 most frequent words
Write a program to which takes an array of digits and prints the histogram of the distribution of digits in horizontal manner. (Vertical histogram and cap on the max value for bonus points)
Two cops and a robber are located on opposite corners of a cube and move along its edges. They all move at the same rate. Is it possible for the cops to catch the robber.
[Each of the 3 people can see each other at all times and can react instantaneously to each others movements. Stopping is allowed.]
given an array of numbers where each number has a duplicate in the array except one number, write a program to return the lone number.
For eg: if the array is 1,8,5,8,1,3,5 then your program should return 3.
given an array of numbers, write a program to return the k largest numbers.
For eg: if the array of numbers is 2,9,6,4,3,8,56,39,5 and k=3 then return 56,39,9.
given a string, write a program to find if it is a palindrome or not.
Render a point if (x,y) cooerdinate.
y*width+x
Explain openGL to a kinder garden
explain heap sort and discuss its complexity
Given an array of balls, which can be one of two colors (RED or BLUE), write a function that partitions the array in-place such that on exit from the function all the balls of the same color are contiguous. It does not matter whether the red or blue balls come first. The return value from the function is the index of the first ball of the second color. If there is only one color of balls in the array then the return value should be 0. It is not legal to change the color of a ball. They must be moved. Consider performance, memory utilization and code clarity and elegance of the solution when implementing the function.
C++ Prototype
class Ball
{
public:
enum BallColor { RED, BLUE };
BallColor Color() const { return _color; }
private:
BallColor _color;
// Other data in class (unrelated to assignment)
};
unsigned Partition( Ball aBalls[], unsigned cBalls )
{
//your code goes here
}
What is the return value of __init__(self): operator? Is there any default __init__ in a class? Can we call __init__()?(anyhow)
Given a string.Replace the words whose lengt>=4 and is even,with a space between the two equal halves of the word.consider only alphabets for finding the eveness of the word
I/P "A person can't walk in this street"
O/P "A per son ca n't wa lk in th is stre et"
Given a very large array of integers, you have to find out maximum difference of any 2 elements in the array such that the larger number has got bigger index than that of smaller number.
for ex -> [2 3 10 2 4 8 1] Ans -> 8 (10 - 2)
Asked me to write a C program which would accept some input strings on command line and then print those strings which are aligned to 80 chars a line..
This was the ONLY sensible question in the entire interview I would say.. Amazon sucks ,,|,,
How can you lock a portion of a file and how to use it ?
IMDB 2.0 - Movie DB Table Structure
Your best friend Betty thinks IMDB (www.imdb.com) is too complicated and challenges you to create a simple movie web site. One page will display movies (with movie name, date it was released, and list of actors). Click on an actor and you’re taken to the actor page (with actor name, birthday, bio, and list of movies actor has been in). Please outline the table structure of the database for this.
Main focus for the interview was memory efficient code and how can we optimize ..
Its better to work on concepts on heap and stack.
tested on the concept of Waiting,Notify..
Explain overloading and overriding. Why would you use each?
Explain projects.
SQL in general, Having clause, Schema, ER, Denormalization.
Reverse a string in Java. Iterative and Recursive fns advs and dis advs.
write a program for placing of n hospitals, in M cities,
distance between the cities should be minimum.
write the recursive expression.
Given a binary matrix, find out the maximum size rectangular sub-matrix with all 1
consider the below binary matrix.
0 1 1 0 0
1 1 0 1 0
1 1 1 1 1
1 1 1 1 1
1 1 1 1 0
0 0 0 0 0
Then the result should be
1 1 1 1 1
1 1 1 1 1
Design Elevator system
Design a Restaurant Reservation System.
Design LRU cache
what is complexity of insertion in trie tree. H needed explanation abt it
Explian the pros and cons of using the spring framework
explain concepts of test driven development, mock tools(for creating and testing mock objects)
explain concepts of java - OOP development.
Questions over spring and hibernate. Explain Spring framework and hibernate concepts. discuss using spring and hibernate together.
class A{ int i;
public:
A(int j):i(j){}
};
class B{int i;
public:
B(int j){i=j;}
};
Which one is faster..uisng the initializer list or initializing in the c'tor body....
Is there any other diff or both will have same performance...??
Given a binary matrix, find out the maximum size square sub-matrix with all 1
consider the below binary matrix.
0 1 1 0 0
1 1 0 1 0
0 1 1 1 0
1 1 1 1 0
1 1 1 1 1
0 0 0 0 0
Then the result should be
1 1 1
1 1 1
1 1 1
assume your computer is reading characters one by one from a stream (you don't know the length of the stream before ending). Note that you have only one character of storage space (so you cann't save the characters you've read to a something like a strong). When you've finished reading you should return a character out of the stream with equal probability.
Unix: You have 50,000 html files in a UNIX directory structure, some of which contain phone numbers in the format ***-***-****. How would you create a list of all the files which contain phone numbers? (Assume that you already have the regular expression)
Given an array of integers where some numbers repeat 1 time, some numbers repeat 2 times and only one number repeats 3 times, how do you find the number that repeat 3 times.
If X,Y and Z are three random variables where their pairwise correlations are the same.
i.e. corr(X,Y)=corr(Y,Z)=corr(X,Z)=rho
What are the possible values of rho?
Oncampus Question:
1) Delete a node from singly linked list given head pointer and pointer of the node.
Variation: How you delete the node given that you cant delet the node. ex: head->1->2->3->4->NULL. How you delete 3 from list given that you can't do anything to node 3.
Write test cases of all.
Return count from an integer array of size 15 when the sum of sub array is 25
If there are two structs, TreeNode and Tree. TreeNode contains 3 elements, data, lChild and rChile. Tree contains 2 elements, int size and TreeNode *root. The tree is a complete tree. So how to find a O(logN) approach to insert a new node.
given a "directed" graph, write an algo to figure out if the given graph is a tree.
convert a binary tree to binary search tree inplace. We cant use any xtra space.
Find the GCD of two numbers.
Why don't we use malloc in embedded systems ? How is memory allocated in Embedded systems ?
You have a string which stores a number with commas. For example, a string that has the number 345,000,000. How will you manipulate this string in-place [without using any extra memory] so that the output is the original string without any commas in O(n) ?
How will you find out if a stack grows up or down in a system ? More importantly, which is better: a system in which the stack grows up or one in which a stack grows down ?
You have a system in which there is a timer that interrupts the system every 20ms. If the system is interrupted, an ISR runs to handle that interrupt. How will you design your system to find if that ISR runs for more than 20ms [in most cases an ISR will be very short...but assume in this case its not] ?
count no. of bits of -ve number
Given two character strings, find whether these are anagrams.
Given a puzzle that there are n statements such that each ith statement says that that many statements are false. Identify the number of true statements for a given N statements.
Q)A collection of n rectangles in the plane, determine whether any two intersect in O(n log n) time....btw a rectangle can be represented as a[4][2] and n such as b[n][4][2]
A calculator with only ":=" and "x". Given a and n, find the smallest number of multiplications to compute b=a^n
Mulitple questions (about 10) about - "how did you?", the situations were mainly evolving leadership issues
Questions about - creating a view, what is a cursor used for, what is an index used for, how to create a procedure query
Explain a time when you did not get alogn with something higher managment wanted to implement. How did you handle that?
Explain what is in a deployment descriptor file? give an example of a deployment descriptor
Explain what is defined in the .jar, .ear, and .web files for a J2EE application?
inplace merging of 2 arrays in less then 0(n*2). I suggested some sorting mechanism and at the same time checking in which array element shoudl go
Consider a language of an Alphabet set. You do not know the precedence order over the alphabet. You are then given a set of words coming from the language in the sorted order. Can you find the precedence order on the alphabet set ? How ? Discuss various cases.
How to completely delete a linked list with circle?He needed an actual code not psuedo code
what is complexity of merging 2 linklist
Give examples of cases where you would prefer to pass objects/variables by reference instead of value?
Given a file containing approx 10 million words, Design a data structure for finding all the anagrams in that set
3)how would you find the unique lines(that are too long to store in memory) between 2 files tat have a billion lines of data each. How will you find the non-unique lines.
Given a constant number of priorities implement a priority queue with O(1) enqueue and dequeue implementations.
Create an object-oriented design for software that allows people to play the card game "War" over the internet. Include the classes, methods, and important variables and data structures in your description.
print out all positive integers from 1 to 100, inclusive and in order and state whether each integer is odd, even, divisible by both 2 and 3, or divisible by 3. design logic to be as efficient as possible.
example output:
the number 1 is odd.
the number 2 is even.
the number 3 is divisible by 3.
...
the number 6 is divisible by 2 and 3.
Intervier: Take any word, remove vowels and place them in reverse order by untouching consonants and place them back. Word is AIRPLANE.
Amazon has two log files that have visitor ids not sorted in any order. One is for today and one for yesterday. Find userid common to them. The files have millllllions of entries in both of them and wont fit in memory..either of them.
Test a DVD player
Perform Sorted Insert on a link list and write test cases
Difference between c++ and c#
Can there exist a loop in a doubly linked list? if so how will you remove it?
Memory Resize Function
Lets say contiguous memory is not available for vector's elements and it is occupied by something else. How does the resize function of vector allocate memory to be contiguous allocation?
vector and list difference. complexities of alogrithms.
how to prevent deadlock.
What is a Deadlock, can you give some examples of real world scenarios where deadlock happens ?
I am trying to merge into a freeway which is completely backed up and cars are moving very slow, is this a deadlock ? If you had to assign a computer science term to this scenarios what would be the closest thing that comes to your mind ?
if base class function and overriding function has different return type how it will impact into main program. lets say base class function is returning int which is virtual and derived class function is returning is String.
and I have base* b = new derived()
so can I call int i = b->function() which is derived class function returning string?
Is it possible to pass arrays by value
Do itoa in O(n). He needed result in 1 iteration we should not reverse string in the end
What do stored procedures get compiled into? What exactly helps them to get executed faster?
Get all information about all threads running. And also where exactly a particular thread is blocked during execution.
Share knowledge about JVM parameters/variables.
How will you go around building a pool of threads in Java? Best way to maintain the thread count once a thread in the pool finishes execution?
What is the difference between class and interface?
What is the difference between an instance and method?
Given 2 array of strings. How will you find the intersection of 2 strings? Write a program in C or java.
Primality Test (function to find a prime number).
In 30 Sec, what is
Thread Pool
Connection Pool
Unix Commands, tcpdump & wireshark.
Test cases for:
Application: Stand alone E-Mail agent on a mobile device.
Clues:
1. Configure (E-Mail Account1 & E-Mail Account 2).
2. Send E-Mail from Account1->Account2)
This verifies handset Inbound & Outbound capabilites
Primality Test (function to find a if given number is prime).
what is conversion operator? Can you convert 1 object into another object using this? if yes How? if not why not?
Can you convert a base pointer into derived pointer? I answered no. Then he asked me what if base pointer holds derived object. I again said no but he told me we can. Does anybody how to do it?
Finding number of on bits (1 bits) given an integer..discuss the various approaches..what is the best one?
Vertically inverting an image (given an input array of pixels and an output array to write to)
Datastructure and algo. for undo and redo of a wordprocessor
Design a parking lot with a condition that park() and unpark() should happen in constant time. Discuss the objects created and how the above functionality is achieved in constant time.
Given a log file which has customer id and corresponding to that id it has a page id visited by that customer. Given such log files for 3 consecutive days, design an algo to find those customers which visited the site on exactly 2 out of 3 days and visited at least 3 distinct pages. Discuss the design and space complexity. Optimize (question is not about using unix tricks)
Algo to check if given binary tree is binary search tree or not. Code it and return true or false. Also it should find the number of nodes in the tree irrespective if the tree is BST or not.
Find diameter of tree. Code it
Given a singly linked list, swap every two elements (e.g. a->b->c->d->e->f->null should become b->a->d->c->f->e->null). Code it such that memory position is swapped and not the node value.
Find sum of all integers of a given number such that sum is always a single digit(e.g. if given number is 987, then sum = 9+8+7=24=2+4=6). Code
Given an array of integers from 1 to N, and given a number X, how many ways are there to pick X elements from the array such that no two elements in the selected X elements are consecutive.
Given a contiguous chunk of a memory, design N queues in it. Make them thread safe.
Implement Queue using Stack.
Given a matrix of characters M and an input string S, find if S occurs in M in horizontal or vertical direction.
A sorted array is shifted circulary(i.e. m elements from start are removed from start and added in the end). So now the array is sorted from 0 to size(array)- m and from size(array)- m to size(array).
Given an element X find it in the array in efficient way. Code.
Return a random element from list such that each element has equal probability of selection.
Given an array of integers (both positive and negative), find the continious sequence having the maximum sum.
Given stock values for a share per day for a company for last say 1 year. Find the maximum loss that any share holder could have made?. Assume that share holder can buy and sell only once. Code and mail after interview.
Design a car rental model
Implement the accessor functions and a CarRental class which contains the container to store them.
A car rental company wants to keep track of its cars. Each vehicle has a license plate and a brand. (eg. BWM). Currently the company has SUV-s and Sedans. SUV-s have an optional third row seat, sedan’s have an optional sport package. Each car can be queried to inquire the number of passengers it can carry.
Have you overloaded operator new ? I said yes then Y did u do that ?
How will you overload << operator for output? Why you have to make it friend ?
What are problems with shallow copy ?
What happen if i delete "this" in member function ? can you call member functions after doing this ?
Have you used any object oriented features in it? What are those ?
You are given an array which consist of number between 0 to 5 digit range. Write a function which will return true or false, if array can be divided into 2 half such a that sum of the two half would be equal
Do know STL , tell me what kind of containers are available , complexities of each ?
You are given a file , How will you find perticular string in file ?
I have given O(n) solution saying i will tokenize strings and use strcmp
You are given an array which contains either 1 or 0 , and they are in sorted order Ex. a [] = { 1,1,1,1,0,0,0}
How will you count no of 1`s and 0's ?
a class contains 2 float and 1 double , what will be size of object ?
Now that class contains 2 floats and static double what will be size ? Reasons ?
Now it contains all static vars what will be size ? Why not Zero ?
What is optimization flag ? Have u used it ? What does it do ?
What is Volatile keyword ? What happens when u use it ? (Expected Ans was compiler puts it into register and hence no optimization )
2nd: Phone Screen
Give object oriented Design of Car.
Design OO model for given movie name and zip code to find nearest theaters showing that movie.
1st Phone screen:
Given a series A,B,C .......Z, AA, AB,AC,AD....AZ,BA,BB...BZ,CA....(Open excel sheet. The names of column represent the series). Given input as number 'n'. Output the 'n' th string of the series.
given 2 non-uniform ropes (each burns down in 1hr, but not uniformly), how to measure 45 mins
Which is the fastest IPC mechanism and why ?
What do you mean by heap fragmentation ?
How do you detect stack overflow ?
What is core dump? Why would you get one? Who generates it?
Explain your favorite project
Reverse linklist in block
eg. block size is 3 and list is
1 2 3 4 5 6 7 8
Output: 3 2 1 6 5 4 8 7
Given an array of numbers, find if sum of any two elements is equal to K (constant).
How to find two linked list are converged or not, if yes where it is ?
A->B->C->D->E->NULL
M->N->C->D->E->NULL
In above examble At node C, it is converged.
One simple solution I can achive using O(n*n), but loking for a solution O(n*2) or O(n*3).
A box contains Red and Green balls...now find the algorithm which arranges all Red balls onside and then all Gren balls
What is the main reason for using pass by reference over pass by pointer
Design a phone book application. He was mainly looking for the data structure. Follow up question was to write a code to insert data into a trie!
pros and cons of any two data structures of your choice (not allowed to choose linked list and arrays)
random number generator
Find all files with US phone number format and print out
How do you debug if safari crashes?
how to initialize the reference member varibale in a class?
Given an array, find elements whos sum is 'S'.
You have a tree with root 1. left of 1 is 2, right of 1 is 3. left of 2 is 4 and right of 2 is 5. left of 3 is 6 and right of 3 is 7.
Level is defined as: Level 1: 4
Level 2: 2
level 3 : 1,5,6
level 3: 3
level 7: 7
Print the sum of each level.
Find the middle element of a singly linked list.
Suppose you are given a dictionary of words based on an alphabet with a fixed number of characters. Please write a method / function which will find the longest word in the dictionary such that it can be built from successively adding a single character to an existing word in the dictionary (in any location). For instance, "a" -> "at" -> "cat" -> "chat" -> "chart".
Design an algorithm to implement google like smart calculator. No button in the calculator. Just enter something like "98F to C" and it should convert 98 degree fahrenheit to celsius.
Calculation part is easy. Design the algorithm to understand what operation needs to be done, whether its temperature conversion or simple mathematics or length conversion
Sort the items in a Stack without using any other container for the items.
There is an ant which can walk around on a planar grid. The ant can move one space at a time left, right, up or down. That is, from (x, y) the ant can go to (x+1, y), (x-1, y), (x, y+1), and (x, y-1). Points where the sum of the digits of the x coordinate plus the sum of the digits of the y coordinate are greater than 25 are inaccessible to the ant. For example, the point (59, 79) is inaccessible because 5 + 9 + 7 + 9 = 30, which is greater than 25. How many points can the ant access if it starts at (1000, 1000), including (1000, 1000) itself?
what is difference between SystemC and C.
given a log file with first field being an url and second being the render time of that page in millisec. find the page with least render time. Url is accessed many times like 50 times or 100 times. every access has an entry so we have to find the average.
return a min from an array? extend this to return kth min element?
The first part is trivial and the second part is selection sort with outer loop running k times.
What is an array? what is a linked list? when would you use an array and linked list?
How would you suffice array with increasing size? or how would you handle dynamic increase on size using arrays. spoke about hash tables.
diff b/w java and c#... Details of how garbage collector works..
Difficult bug and how you resolved it.
Generate anagrams. complexity
Given a node in an SSL, delete it..
winamp or any media player random play a plalist feature
Bsically the question is to design a "Shuffle Play" feature which ensure that all the songs can be played once in random fashion with best efficiency.
network ip add is given in str form
read dat, parse it and from left to right
push into integer
4 parts of ip . each part can be stored in one bit
There is long list of natural numbers.
Remove every 2nd no from list in 1st pass
Remove every 3rd no from list in 2nd pass
Now find whether nth natural no will exist after p passes. n and p are inputs
design a int server
say user are having acc for five servers
say data base of diff info
now u need to design a integration server
so that if u change the password for one server
it will change the password on all five.
another part is to write the prototypes of APIs which u will use.
find head of Linklist
An array of linked list nodes are given and act as pool of nodes.
A list use a free node from array to make new node.
When list want to free a node it just changes pointer.
Case 1: No initialization of nodes happen.
Case 2: Initialization of nodes happen. means next pointer is set to NULL.
Now look at array of nodes and find the head of linked list. Can you find it. Why or why not.
How to find optimally. Tell for both cases.
There are 3 files in a program.
// File: foo.c
static int var;
void foo()
{
var++;
}
// end of file foo.c
// File bar.c:
static int var;
void bar()
{
var++;
}
// end of file bar.c
// file main.c
static int var;
void main()
{
foo();
bar();
printf("%d", var);
}
// end of file main.c
Question: Will the above program compile ? If so what will be the result ?
Probability question: Persons A and B go shopping together. Say person A spent X amount of money and B Y. What is the probability that the sum total of their purchases [i.e. X+Y] has 0 cents [i.e. is a whole number]. ?
Why is this not allowed in C++ ? Explain problems with this approach
Derived *d = new Base()
If I create an object of class Foo, and send its address and sizeof to memset and set it all to 0, will it work? I answered yes, it ll set it to 0.
then he asked, if everything sets to 0, will u still be able to call functions? i answered yes, but if the function uses any data, it might not work, as data would have been corrupted.
he asked, will any function not work? yes, if there are virtual functions, call to virtual functions will fail, as pointer to vtable will be corrupted.
implement a function to_dollar(int a) that takes in an int, say '10200', and prints $10,200.
write the prototype for strcat function in C
why do u want to work at bloomberg
how do you handle the deadlines when there are other important things happening.
Print the longest sequence of numbers that appear in ascending order in an array(need not be contiguous). Suppose your array has values a={8,6,5,1,9,3,7,4,2,10}, the output would be 1,3,4,10.
Explain all the packets exchanged/transmitted by your system from the time of boot to the time I try to access google.com
How to find the maximum rectangle in a histogram, and write C++ to implement it.
write a function that accepts an array, a number. it need to find the first two numbers in the array to have the sum as the number passed. You know the length of the array
You have a stream of sentences. you don't know total number of sentences until you exhaust the stream. you have to choose one sentence randomly from the input stream. you don't have space to store all sentences at your end. randomly means probability of choosing any sentence is equal.
Class Design:
Using char*,
design an CString implementation.
List the functions that are supported,
Implementation of "operator=".
Static members,
What are they?
Their reason of existence?
Challenges they have? (Link initilization)......
I/P: Set of Words
O/p: Group anagrams and print them on same line.
An investment, 16% chance to lose money on a quarter, and each quarter follows i.i.d. normal distribution.
Q: what is the probability of losing money by the end of the year?
You need to spend an exact amount from given types of coins of various denominations. There is a cost associated with the type of the coin. You would like to minimize the cost subject to constraint that you can only spend a limited number of coins of each denomination
Input :
coinDenoms = {100,100,300,400,500,600};
coinDenomSize = 6
coinCost = {125,150,425,525,625,725};
coinCostSize = 6
amount = 400
limitPerDenomination = 4
Output :
The function findMinCost() returns an array containing
125,125,125,125
Suppose two lists merge at some node .. how do you find that particular node ..
Given an array one set repeats once, one set repeats thrice, rest all repeats twice .. XOR method only .. (No Sorting and Hashing)
Implement strstr()
What is DOM? How is it useful ?
Detail design of software which work exactly like "http://tinyurl.com".
reverse a string in one pass inplace too.....I have no idea :(
find the maximum sum of a matrix
do inplace sorting of arrays in less then 0(n^2)
A semi-connected graph is a graph that for each pair of vertices u,v, there is either a path from u to v or a path from v to u. Give an algorithm to test if a graph is semi-connected.
Given a string and a array of smaller strings. Design a method to find out every occurence of smaller implementation in larger string.
What kind of role you are looking at Microsoft?
#1. Implement (in C++ or C#) a function that removes the nth element of a single linked list.
C++:
class Node
{
char* value;
Node* next;
};
Node** RemoveNth (Node** list, int n)
{
}
C#:
class Node
{
string value;
Node next;
}
Node RemoveNth(Node list, int n)
{
}
#2. Using the following table provide at least 5 test cases to test the function implemented in the previous part.
Node n Expected Result
~~~~ ~~~ ~~~~~~~~~~~~~~~~~
Write a function that would: return the 5th element from the end in a singly linked list of integers, in one pass, and then provide a set of test cases against that function
If you want to add a new feature to Amazon.com website like this: Whenever a user requests for an item, and it is not available, he should be able to subscribe for that item, such that when at a later point in time the item is available, he gets an email. Design an approach for this!
Find the intersection of 2 lists
Can you have dynamic arrays? If yes, how do you implement it. When I mentioned about creating a larger array and copy all elements to it, he was curious to know what would be the size of this larger array.
Difference between Arrays and Lists. Discuss pros and cons.
What is Full binary tree and complete binary tree. And code to find if a given tree is so.. (Phone interview, interviewer was very supportive. As I couldn't finish coding, asked me to send offline, and did so).
detecting deadlock
how does tcp and udp together react
how does tcp react in wireless, different tcp versions
implement atoi
how to make multicasting reliable
why copy constructor must pass by reference
Given an m x n binary matrix. Find the maximum all 0 submatrix (not necessarily square submatrix).
class Person{
public:
Person(const char* szName);
const char* GetName() const;
/*put a function here*/
private:
char *m_szName;
};
int main()
{
Person person("John");
std::cout << Person;
return 0;
}Referring to the sample code above, which one of the following member
functions do you add at the comment to support std::cout << person
statement?
A. std::string operator() { return GetName(); }
B. std::string ToString() { return GetName(); }
C. const char* Convert() const { return GetName(); };
D. char* operator char*() const { return GetName(); };
E. operator const char*() const { return GetName(); };
Why does your class have a pure virtual function?
A. To ensure that this function is overridden in derived classes
that are to be instantiated
B. To allow for templated classes to be used with friend functions
C. To maximize the memory efficiency provided that execution speed
is not at a premium
D. To maximize code reuse
E. To maximize the execution speed of the function provided that
memory is not at a premium
you are given a M x N matrix with 0's and 1's
find the matrix with largest number of 1,
1. find the largest square matrix with 1's
2. Find the largest rectangular matrix with 1's
Non Preemptive scheduling :-
write a program to list the waiting time of the processes based on the arrival time and the burst time under non preemptive scheduling. In the Non Preemptive Scheduling, he current process keeps the CPU until it releases the cPU by terminating. The operating system never initiates a context switch from a running process to another’ process.
when there is more than one processes waiting for the cPU, the process which will release the cpu first by calculating the sum or arrival time and burst time, will be allocated
Example:
Process 1 3 2 4
0 7 8 12 16 Start time of the process the waiting time should be: 0, 6, 3, 7
I was asked to find the pair of numbers in an integer array that would sum up to make 100. The function would take the integer array as an argument. I replied him using Bubble Sort with O(n*n) but he wanted me to do it with O(n). Does any one know how to do it with O(n) ??
Given three lists: A, B and C of length n each. Write a function which returns true if any 3 three numbers (1 from each list), sum up to zero. Else return false, if there is no such combination.
Write a function to find the nth last element from a Linked List.
What is a hash table? Why is it better than other data structures? Compare hash table with tree? Discuss advantages of one over the other.
Whats the size of a derived object ? How would you calculate it ? Does it include size of base class size?
Can you do this : Derived *d = new Base()
Where base has a virtual func foo() that is also implemented in derieved.
What are the implications ? (Note: its opposite of what one does for polymorphism..)
How do you perform error handling in destructors ? (throws Exceptions?)
If a base or derieved class does not have any members that are allocated on heap, would you still use a virtual destructor ? Why ?
Given a URL string, replace every space in the string with %20.
Find least common ancestors of two nodes in binary tree with parent pointers, without parent pointers
How do you get the request URL in a servlet?
what will happen if you do not use hashcode() to override a equals()?
Calculate time complexity with given an executable file which basically performs a sort operation on text file with n numbers.
Reverse an integer array bitwise algorithm? code? Test cases?
Convert a Roman Numeral string to Decimal. algorithm? code? Test cases?
Given a linked list, output a random node of this linked list. Ask details about what exceptions might be thrown in the implementation.
With minimum number of steps read the last 5 line of a log file.
What are matched and unmatched exceptions in Java?
There is a stream of characters interleaved with \n's. Thus it is a stream of lines. You can only go through the stream once and you have only a constant buffer eg 10 slots. Thus you can buffer only 10 lines. Now, if I pick a random no. between 1 and the total number of lines, how will you retrieve it?
There are 3 boxes. One has only black balls, one has only white and one has mixed. All three have the wrong label on them( eg. black, white and white). You can pick any no. of balls from any box. How many min balls can u pick to determine the right labels for all 3 boxes?
Lone tester interacting with the test team.
How would you communicate and moderate with Test and Development teams?
I/P: CareerCup
O/P: p_Cr__r_C
Tasks:
1. Reveres the string.
2. Replace every vowel with space.
Tell me about your involvement in Test Planning process.
Tell me about your experience in classifying test cases at different phases: Feature, Regression, Performance
What are some typical examples of challenges with GUI testing?
Classic 25 horse problem,
25 Horses,
Have a 5 horse track,
No stopwatch,
How many races are required to determine the 3 fastest horses.
How do persevere in a problem or bug identification, when the dev team has different opinion?
find maximum sum of matrix.
he asked me to come up with the code for wild card character matching and then test it
find the longest word made of other words
Given a graph represented as 2D array. How to find whether graph is connected graph or not?
write 2's complement for -5
What is the difference between >> and >>>?
What is transient variable?
Write an algorithm to find if 2 binary trees are equal (as in the data of the 2 are equal)
Why would you use the JSPs and JavaBeans in a web application?
There are 7 buckets of water and an infinite number of flies. One of the the buckets is poisoned. You need to find which one is poisoned by putting the fly in it. It will take 7 days for the fly to die and and for you to know that the bucket is poisoned. Also you need to send one of the (non-poisoned) buckets to your friend in 1 week. How will you find out the poisoned bucket in least number of flies?
how do u multiply a number by 7..tell an efficient method
You are given a String number containing the digits of a
phone number (the number of digits, n, can be any positive integer) . To help you memorize
the number, you want to divide it into groups of contiguous digits. Each group must contain
exactly 2 or 3 digits. There are three kinds of groups:
• Excellent: A group that contains only the same digits. For example, 000 or 77.
• Good: A group of 3 digits, 2 of which are the same. For example, 030, 229 or 166.
• Usual: A group in which all the digits are distinct. For example, 123 or 90.
The quality of a group assignment is defined as
2 × (number of excellent groups) + (number of good groups)
Divide the number into groups such that the quality is maximized. Design an efficient
algorithm to return the solution that maximizes the quality.
How would you store pictures from Google's street view? (assume massive amounts of high quality pictures)
Multiply two numbers without using multiply(obviously),division,bitwise operators and no loops.
For example: 3*2=6 without *,/,bitwise operators and no for,while loops.
Hint: Answer using recursion..
Find the Max. sum of two elements in a Matrix.
Find the Max. sum of three elements in a matrix.
Find the max. sum of K elements, where k < n, in a given matrix.
In 2d array declaration or defintion of a function the first dimension argument is optional, why ?
and how it will works?
Describe and algorithm and implement UNIX tail command
Explain what is a weak reference. How do you declare a weak reference? Why would you implement a weak reference - versus a strong reference?
Write a function to compare two xml files
bool CompareXMLFiles(string fileName, string fileName);
Scenario
1. Path to files are given
2. We have to compare the content of xml files.
3. Xml with different element position would be same i.e.
<Tests>
<Test>UI<Test>
<Test>Functional<Test>
</Tests>
is same as
<Tests>
<Test>Functional<Test>
<Test>UI<Test>
</Tests>
4. Different position of attributes can be there e.g.
<Test Id="4" No="50">Functional<Test>
is same as
<Test No="50" Id="4">Functional<Test>
5. One Xml file can contain comments and other can/cannot but this is same
Within a 2D space, there is a batch of points(no duplicate) in the region (0,0),(0,1),(1,0),(1,1), try to find a line which can divide the region to 2 parts with half points in each .the input will be an array of points and the length of the array.
struct point{
int x;
int y;
};
input : struct point * points, int length
Given a string which may contain one or multiple spaces in between the word characters. If there are multiple whitespaces, replace all with single whitespace.
Constraint -
1. Do not use any extra char string or array
e.g.
char *string = "Test-String----to-be--displayed-";
The string should be replaced like
'Test-String-to-be-displayed-'
Consider '-' as whitespace.
Given a Queue Perform following operations -
1. Enqueue
2. Dequeue
3. Max
Constraints -
Max has to be implemented in such a way that complexity should be O(1)
What is the purpose of the session() in a servlet?
How does hiberante handle atttached objects?
Can you have mutliple instances of a database running in hibernate?
Create a balanced binary tree from a given link list
Given an array of integers where some numbers repeat 1 time, some numbers repeat 2 times and only one number repeats 3 times, how do you find the number that repeat 3 times. Using hash was not allowed
Given a n*m matrix having numbers such that each row and each column sorted. Now print the numbers in present in the matrix in sorted order... I tried to explain k way merge sort but he didnt wanted that. He was loking for better sol.
Write a code to calculate kth power of a matrix of size nxn. You can assume that matrix multiplication is O(n^3).
find the diameter of tree
How can I write a macro which takes a variable number of arguments?
Write C code to implement the strstr() (search for a substring)
function
For 0<=i<=9, array defined is T[i] = i . Now construct another array T[j] for 0<=i<=9 where T[j]==m if T[i] appears m times in T[j].
Print tree level-order traversal but starting from the depth i.e The lowest level should get printed first and the root node should get printed last.
A point in 3-d is defined by (x,y,z). Distance d between any two points (X,Y,Z) and (x,y,z) is d= Sqrt[(X-x)^2 + (Y-y)^2 + (Z-z)^2].
Now there are a million entries in a file, each entry is some point in space, in no specific order. Given any point (a,b,c) find the nearest 10 points to it. How would you store the million points and how would you retrieve those 10 points from that data structure.
1) There are two hashmaps with string as keys and double as values. Construct a method which takes in these two hashmaps and returns another data structure which returns difference between the values with corresponding keys.
Q)A collection of n rectangles in the plane, determine whether any two intersect in O(n log n) time....btw a rectangle can be represented as a[4][2] and n such as b[n][4][2]
Written test followed by Interview
Written Test: 1 hour 20 minutes Duration
15 questions on java, SQL,C++ total 45 Q
you need to pick up 2 sections , i choose Java and C++
total 30 q + 15 q on Analytical its mandatory
all together 45 questions
there is one Subjective questions on java, SQL,C++
you need to pick 2 out of 3
So all of them need to be answered in 1 hr 20 min ....
after 2 hours results are announced
i cleared Written test
then interview : asked about singleton model , som basics of java and 10! recursion .. later genral questions...
Algorithm to solve sudoku puzzle
code to find transpose of a matrix using only one array
big endian and little endian Q
what does the volatile keyword in C mean. where is it used
write a c code to reverse the bits in a uint8 type variable.
write a code to count the no.of 1s in a given 16 bit integer.
you are given 2 crystal balls. there is a 100 storey building. what is the minimum no.of trials you need to make in order to find the nth floor at which the crystal ball starts to break. note: if the ball doesnt break, you can reuse it.
give an array, remove all the 'a's and add one 'd' after each 'b', do it in O(n)...
given a stream of integers.. 112233344442222 write a finction that would return as 1222334424
what are the complexities avg and worst cases in adding an element at the end, middle of the Array list...
How would you add an element in the middle of the array...
Given a general tree(non-binary) , with a root ; serialize it ( ie convert it in a form) such that it can be written to a file. We should also be able to reconstruct the tree looking at the contents of the file.
worst case and average case running times of quicksort, merge sort, heapsort and when will the worst case occur?
indexes in databases use which data structure? why?
why maps have constant time for retrieval, adding and deleting.. internally what happens?
explain how hash function in maps work..
how to handle collision of hash values?
what are tree maps?
what is the great advantage of using hibernate(or any ORM) vs. direct peristence
Interview for mid-level java developer:
problem-solving skills question:
You have a page with a main menu and then submenus. depending on which menu button you press different set of submenus is shown. when the user presses on a submenu button they are sent to that page by a link. You want to setup a breadcrumb in the URL to show where the user has been - pressing the main menu, then the submenu the link for the submenu should display in the URL(example. page1/page2/?link=_...).
Issue: link keeps changing -
The user clicks the menu, the submenu is shown, then they click on a submenu, then they go back to the main menu, then click on the same submenu as before a different link is seen. but it should be the same link since it is the same menu to submenu combination.
how do you solve this issue?
** this was a "feel-out" question. I later found this out it wasn't meant to be a question i was suppose to be able to answer correctly but a question to test an individual's problem solving when on a diffuclt problem
Explain the different types of EJBs
What does the web server contain? what does the application server contain? Basically, explain how the tomcat server works different then like a JBOSS server
Implement a Singleton
Virtual Functions and its implementation
Explain Indexing, Mining algorithms, Joins, SQL
Hashmap and its implementation.
Given a IP address, Validate the IPaddress. The IP address lies between [000.000.000.000]-[255.255.255.255] .
IP address is in String, hence you can fetch the characters in the string and move ahead. Hint: use Regex
4. Tell me the steps involved in insertion and deletion of a node from skip lists.
I told the steps.
and he asked for time complexity...... I told him O(log n)
3. You have a grid with mxn matrix.
and every edge is associated with some cost. at any time only x-cordinate or Y- coardinate can increase, no decrease operation.
1. derive a recursive relation to get the max.cost
my ans: a[i][j] = 0 if i=0 and j=0
max(a[i+, j], a[i, j+1] ) + cost a[i][j]
2. Then Asked for the 2nd max. cost.
my ans :
find the min. difference with previous node, in the entire path,
and remove the difference from the max. path cost.
3. Then asked for kth Max Path cost.
my Ans:
when calculating the path cost with previous node, store the differences in an array,
and find the kth, min. in the difference array and subtract the difference from the max. sum.
1. There is a stream of numbers, design an effective datastructre to store the numbers and to return the median at any point of time.
my answers:
1. Arrays. (static DS)
insertion time O(1)
media time --O(1)
2. Dynamic DS.
Linked list: with two pointers.
head pointer and median pointer.
median is pointer , which will be incremented on addition of every two nodes.
insertion time 0(n), can be reduced to 0(1) with the help of tail pointer.
median time 0(1)
Skip Lists:
Insertion time o(log n)
Median time 0(log n)
test MS Excel cell
This was a question for a java developer position:
Why would one choose to use a DB2 database vs. an oracle database?
Can you describe the differences between java 5 and java 6. Also, can you describe some of the newer enchancements in java from java 1.4 to java 5.
this was a question for a java developer position:
A web application is running with the following architecture - they have 6 database servers, 4 business servers, with 4 different web servers. Question: why would a web application be running their architecture this way? Can you describe the architecture of your last project
Can you identify 10 different Java APIs and explain what each is used for
Can you explain what is the difference between DOM and SAX. what is DOM? what is SAX? What are the differences between the two. when would you want to choose one over the other.
Can you write a program to create a deck of cards, with the two joker cards
Interview for a mid-level java developer on one of their product R&D teams:
Can you explain the use of web application frameworks in java development. Discuss, how they work, why they are used, what they have done to revolutionize java development in the last few years. Can you explain the difference between Spring and Struts. Can you explain the similarity between the two.
Mirror a binary tree
Power Set and Permutation of a set ?
Given an array of n numbers in which all the members are less than or equal to k (k<n). device an algorithm of order O(k) to find the first repeating element.
How do you write a de-constructor in Java? Explain how is it used in programming and how Java handles this issue.
How does the Collections API handle collisions? How does the API handling making the collection "some-what" collision safe?
Explain- which collection does this affect and the best way to deal with it.
Also explain, the most common senario that causes this issue- hint* one is in threading(how can this be caused).
Write code to find the nth factorial
You need to organize a football tournament. There are n teams given. You need to prepare a schedule for the matches so that each team plays with every other team and on the same day no team plays twice. You want to finish the tournament as early as possible.
Hi all, I had MS interview today on campus. He asked me to implement a function readone().and also gave me an input file with lot of lines. This function readone() should read the file(just one line from the file) whenever it is called.for example, if readone() is called first time - it ll read first line, if readone() is called second time, it will read second line. Though the qn seems simple, I baffled there!:(
how to find the msb in smallest no. of steps
Given 5 prices of a share for 5 days i.e. from Monday-Friday share prices for a perticular share are $1, $4, $5, $2, $3. Find the max profit you could make in a given week. You are not allowd to do multiple trading in a day and its not mandatory to do trading on each day. Write a C code for this.
1. Explain OOP,classes,inheritance and polumorphism.
2. Difference between C,C++.
In a very complicated Java back-end system, since the load is too big, the garbage collector can not handle the memory and start having memory leaks. How to detect it and solve it?
What is the difference between a C++ array and an STL array type
There are two nodes given in a tree(not binary tree). Find wether one node is parent/grand parent of other.
order should be O(1)
What is Spring IOC?
What is a deadlock and what are some of the ways to avoid a deadlock?
Explain hashcode() and equals() methods? When would you override these methods? What does the hashcode() method in the Object class do?
What is an immutable object? How do you implement one in Java? How to construct an immutable object that has an array/List as one of the instance properties?
Implement copy-on-write string class.
job: BUILD ENGINEER
Hi This is the question in my 3rd round, last question.
(after completion of DS round)
i have three files.
f1.c --- uses add() and sub() function,
add() it is defined in f2.c.
sub() it is defined in f3.c
How will you compile on gcc, with out using any make file.
please tell me the procedure.
what is composition?
find nth largest element in an array of m elements where n->0 (n is much smaller than m) without sorting
design deck of cards.
return the common string from 2 strings of arrays in optimal running time.
you are given the data value pair of nodes in a tree. construct the tree. e.g. lets say root has two children and root's data value is 5 and one child's value is 8 and other child is 10. you will be provided 5,8 and 5,10. you need to construct the tree. this way you will be given all the pairs.. construct the tree
Given a table:
TABLE
Cust ID, Order ID, Date
Retrieve the customer who has ordered on two days ie., say 1st and 10th.
Also, is your query the most optimal one.
Have you ever had a conflict with a teammate? How did you handle it then?
Explain what was the most challenging thing you have ever done?
How would you go about designing a website for providing credit card and other services for commercial banks?
Given a diagonalizable square matrix A and a noise matrix E, find conditions on A and E such that for each eigenvalue L of A, there is an eigenvalue M of (A+E) such that abs(L-M) < K for a given K. (this is obviously an open ended question, try to tighten the bounds to the best of your ability)
Program takes 3 inputs startdate,enddate and dayoftheStartDate.We should return the enddate day of the week.
Example:StartDate=2/25/2010 ,EndDate=2/26/2010,"Thurday" and outputshould be "Friday"
char a[] = " ";
Q. What will be sizeof(a)
class Foo {
public:
void virtual abc() throw (int , double, long) {
};
};
class DFoo : public Foo {
public :
void abc() throw (double , int , long ) {}
};
// Will it compile
int main(){
DFoo d;
return 0;
}
Go through all the C++ Qs put on careercup , in online test most of these Qs repeat .
// Online Test
class Someclass {
public:
int x;
public :
Someclass(int xx) : x(xx) { }
Someclass(const Someclass& a) { x = a.x ; x++;}
Someclass& operator =(const Someclass& a1) { x = a1.x ; x--;}
};
int main( )
{
/*Someclass a(4);
Someclass b = a;
}
Q. What will be output
Take a tree (binary or otherwise), write a method in any language that, when given the root node, will print out the tree in level order. With a new line after the end of every level.
Helper methods are ok, big O run time efficiency doesn't matter (though obviously a quicker solution is better). Do not destroy original tree.
1) Bus route Database -
I want to design a database about bus route of a city like bangalore. Where u know all bus stop name and need a DB such that it will be easy to add new bus stop in our list. We would like to handle two kind of queries a) user will give route number ......we have to retrieve whole route i.e we have to print all the bus stop where this bus will stop and b) user will give source(S) and destination(D) name .....we have to find all possible route number that a person can take to reach D from S considering one case where we dont have direct connectivity from S to D so it should show via routes as well like the results of makemytrip.com or yatra.com when u want to travel from bangalore to guwahati ..though no direct flight is there we will get some via list. Also DB should be easily expandable (ie their should be some easy way of adding new routes and stops).
Given a set of pairs of key-value..ex:[1,2],[2,4]..such that 1 maps to 2 and 2 maps to 4. Now give a data structure and a solution to print the output such that any key from the input appears before to its mapped value.
For ex: input [1,2](now 1 should appear before 2 in the output),[3,6](3 should appear before 6 in the ouput),[2,5](similarly..)
and the output is 1 2 3 5 6
Note: the key value pair is gone in the output.need not worry for that.
Given a cube. A ant is placed in a corner and cannot move. A spider starts from the opposite corner, and can move along cube edges in any direction (x,y,z) with probablity 1/3. What is the expected number of steps for this spider to get to the ant?
Find out duplicates from unsorted integer array (including -ve and + ve numbers).
State different approaches and complexities.
If using sorting approach which sorting algorithm you will use??
Return whether a given string contains any palindromic substring or not....again complexity discussion and other ways of doing it using suffix trees and discussed complexities of approaches.
Selection sort algorithm and code it...discussed complexity of it...what is big O??? what do we mean by exactly finding out run time complexity?
Discussed other sorting algos and their complexities
security code takes numbers but one key is allowed to be faulty, other numbers should be same in sequence ex 124 is accepted if actual number is 12646..
You are given a segment with length 1. Randomly pick two points from it. What is the expectation of the distance of the two points?
Given a n-by-n matrix, and computers as many as you want. Design a distributed algorithm for self-multiplication of the matrix, which is stored in one of the computers. What is the time complexity of your algorithm? You need to reduce the time from O(n^3) that is the time for multiplication on a single computer.
Given a time find the angle between hour and minute hand
Reverse a linked list
Reverse a linked list.
Design an elevator.
Design a furniture management system. You will have have to design class Furniture, WoodChair, SteelChair, WoodTable, SteelTable, etc. Each furniture has material(s) -- wood, steel, cotton. You have to design functions: applyFire(), applyWeight(), etc. Make your system easy to extend in order to include more materials and more subclasses like Futon.
Design a cache by Least Recently Used method (LRU).
What keywords would your peers use to describe you, and why?
What do you know about our company?
Explain these terms: SCSI, FCP and iSCSI.
Tell me about a situation where you had to speak up in order to put across a point that was important to you.
Describe a time you failed at something. How did you handle it?
What interests you least about this job? What did you enjoy least about your last job?
How would you design parallel access to a filesystem?
How would you test a soda machine?
How would you implement the Unix fork() system call. What are the data structures involved in this process?
Name a few UNIX filesystems you have come across.
What is the use of the superblock in a UNIX filesystem?
Compare and contrast a filesystem and a database.
We have 3 declarations of the variable in in 3 C files as follows:
int i=100;
extern int i=100;
static int i=100;
Now we feed these files into a compiler to create one program.
What happens?
What's the most important thing you've learned in school?
What are two positive character traits you don't have?
Can you describe a time when you were criticized for your work?
Discuss the advantages and disadvantages of using a hash table and a binary tree.
Explain the terms: latency and throughput. How are they related and how are they different?
Discuss one of the small innovations you made and how it led to solving a real life problem.
Explain how a context switch happens.
What does the wmb instruction do?
Write a program to reverse the order bits in a number. Try to optimize it.
What is firmware? What is a device driver? How are they related and how are they different?
What all did you do to improve the conditions in your college?
What is a snapshot? Why is it useful?
What is the tradeoff involved in increasing the RAID stripe size?
Can we assign a hot spare to a RAID0 array?
What is the difference between RAID 0+1 and RAID 1+0?
How are system calls implemented?
Add two 64 bit numbers on a 32 bit machine.
Describe what happens in an ISR.
Without using sophisticated debuggers, how do you estimate the memory usage in your program? (Stack/Heap)
Explain what happens when you called the fopen function from your program.
How would you go about designing a SMP scheduler?
Find the two closest values (fabs) in an array of float numbers.
If you have multiple threads waiting on a mutex, which one gets the lock when it is released?
Given a Binary tree, create a mirror image of it.
Give me an example of when you had to go the extra mile to meet a project deadline.
Describe the key differences in NAS and SAN.
Describe the function of the Heap in an Operating System.
Write a C function to return whether the stack grows up or grows down.
What happens during a page fault? a segmentation fault?
Describe what happens when a function is called from another function.
Tell me about your projects mentioned in the resume.
write a function ftoa(float n)
Give a Tree, create a linked list such that each node in the list is sum of nodes of tree in each level.
example:
Tree
2
/ \
1 3
then list should be
2->4->NULL
I answered the question well but did not clear the round :(
Write code for finding length of largest monotonically increasing sequence in an array of integers.
Optimize it (not the usual O(n) in worst case, but a better approach in average case).
How do you write a TCP server? Give pseudocode.
Explain how a byte in a file is accessed. Let us say you called getchar() on a file you open. Explain what happens behind the scenes from opening it till giving you that one byte.
How do you implement memcpy? What can go wrong and how do you fix it?
A car travelling with a speed of 100 km/hr reduces it speed at 2km /hr.What is the peed of the car after 5 hours.
Given two pointer in a tree find the nearest parents of those pointers place in a tree.
Convert any BST into doubly linked list inplace.
//Online Test
extern void print(int *ia, int sz);
void print(int *ia, int sz);
Q. Will it compile
//Online Test
struct A{
int i , j;
A(int ii , int jj) :i(ii),j(ii){}
A(const A&a){
cout << a.i << a.j;
}
void operator = (const A& a){
cout <<a.i << a.j
}
};
Q. A a(1,2);
A b(2,3);
A z = (a = b);
what will be output
//Online Test
template <class T>
struct sum {
static void foo(T op1 , T op2){
cout << op1 <<op2;
}
};
Q. sum::foo(1,3); will it compile , what will it take to compile
//Online Test
class Base {
public :
virtual void method () = 0;
private :
int n;
};
void Base::method() { n = 1;}
class D1 : Base {};
class D2 : public D1{
int i;
void method() {i = 2;}
};
Q.Does it compile , what will it have to add to compile
//online Test
CLASS A{
PUBLIC :
INT &I;
INT J;
A(){
INT J;
I = J;
}
};
//Where to init reference , in member init list or ctor
//From online Test
class String{
public:
explicit String(char ch , int n = 1){}
String(const char *p){}
private :
void operator=(const char*){}
};
Q.Will it compile
You are given an array containing only 0,1 and 2. Sort this array in one pass.You can't use anything like counting the no. of 0s and 1s.
Write code to find the median of a binary search tree.
You are given an array and a key.Find out whether there exist two elements in the array that sum up to the key.Write all possible test cases.
You have a sorted circular linked list but you don't know the sorting order(increasing or decreasing).Write code to insert a node into this list.Take care of all the possible cases.
what is strong typing/weak typing
find maximum number in an Array of elements
Design a Chess Game
Given n elements, sort the elements. Here, only one operation is permitted decreaseValue..
Note that you cannot swap the values.. output should be a sorted list..
if input is 4 5 2 1 3
output is 3 3 3.. There can be many answers.. Give the optimum solution with minimum cost. where as cost is the sum of decreased amounts..
for this example, 4,5 are decreased by 1.. 2 is decreased by 2.. 1 is decreased by 1..
How do you write a ping routine in Java
you are getting an infinite binary stream of characters then after any point of time you need to print whether the no is divisible by 3 or not, how will you do that?
find meadian of a BST, with out any extra memory and with out using any gloabal or static variables.
3. Given a NxN matrix with 0s and 1s. now whenever you encounter a 0 make the corresponding row and column elements 0.
Flip 1 to 0 and 0 remains as they are.
for example
1 0 1 1 0
0 1 1 1 0
1 1 1 1 1
1 0 1 1 1
1 1 1 1 1
results in
0 0 0 0 0
0 0 0 0 0
0 0 1 1 0
0 0 0 0 0
0 0 1 1 0
Given a set of tasks with a duration and a deadline, how do you define a scheduling algorithm to minimize total lateness? and how to minimize # of late tasks?
Given a set of N elements, how would you select all combinations of K elements? How about all combinations of all elements?
So if there is a list of items {1, 2, 3, 4, 5},
how do you select all possible combinations? {1, 2, 3, 4, 5, {1, 2}, {1, 2, 3}}....
What is the algorithm to count the number of
bits in a 32-bit word. What is the optimal solution as well?
write program to inverse order of a given integer.You can not convert integer into string and convert back.
Differences between C++ and Java polymorphism
Differences between C++ and Java
Differences between C and C++
Find the deepest common ancestor of two nodes in a tree structure. Depth of a tree grows towards its leaves.
root is the least deep node in a tree.
Reverse a character array(string) in C in a single pass without using any buffer!
e.g: Reverse the char array "today" to "yadot" (without the use of any buffer!)
2. Write an efficient program to find an element in a two dimensional matrix, the rows and columns of which are increasing monotonically. (Rows and columns are increasing from top to bottom and from left to right).
Show that second smallest of n elements can be found with n + logn -2 in worst case..
Heap during finding the minimum???
I would like to know what exactly is Multitasking and Multithreading and Multiprocessing w.r.t a computer system which has a single processor?
I would highly appreciate if someone could explain me beyond confusion at the earliest.
Regards,
Srinivas
What is the difference between initializing values using overloaded new and the constructor???
Find common elements in two linked lists.( complexity less than NlogN )
asked simple question about context switching, advantage/disadvantage of process vs thread etc
find top 3 horses of 25 with minimum no of races. u dont have clock to measure timing of horses. maximum 5 horses can participate in one race.
find top-k element in an integer array of size n
What do you mean by virtual destructor? How do you design an ISR? what do you mean by priority inversion? Explain the difference between a semaphore and a ISR?
Suppose you have 2 threads which are started asynchronously at different times and you a synchronization point where if any one of the threads reaches that point before another thread it has to wait till the other one reaches there. How do you design this?
What do you mean by a RAW socket? What is the endianness followed in the network?
Suppose you have a application running on a TCP with 100% functionality. Your boss asked you to change the application so that it works on a UDP but you should maintain 100% functionality similar to a TCP one..how do you design this new UDP based application?
int *p;
char *q;
printf("%d",p+1-p); --->1st
printf("%d",q+1-q); --->2nd
Lets say p is pointing to the variable address in 1000 and q is pointing to the char variable in the address 2000.
Then he asked me to explain those printf statements...and the next question is why the 1st printf is not printing 4 but it prints 1.
What happens when you change the MAC address of machine with a static IP address in a particular subnet?(he was expecting the ARP in the subnet)
What do you mean by sockets? Explain the socket programming when you are designing a server?
Which data structure would you use to implement a cache (LRU or MFU) and why?
Write a program which prints itself. and no input is provided.
Reverse a linked list with atmost two extra pointers.
Design an efficient Data Structure for a Tic Tac Toe game.
Test cases for a calculator
Recursive and iterative soln to generate fibo series ..
What is your understanding of communication.
Explain computer networks to a kindergartener.
Write a function that would have as input a string,and list of characters to be deleted from the string.
Write Test Cases
How would you reverse the output string?
How to write our own rand() function ?
How to do inheritance in JavaScript?
What is JavaScript closure?
find the Nth largest node in a BST
This is a question on scheduling meeting in a calendar.
Suppose we want to schedule a meeting amongst 3 employees. When we select them it has to show available time slots free for a meeting.
Example:
Emp A: 9:15 to 10:15; 10:20 to 11:20
Emp B: 9:30 to 10:00; 10:25 to 11:15
Emp C: 9:00 to 10:00; 11:00 to 11:10
...
Given two sorted integer arrays A and B of size n and m respectively, find the kth smallest element in the union of A and B in O(lg(n)+lg(m)) time....
Consider a matrix of integers with m rows and n columns.All the rows are first sorted.Then all the columns are sorted.
Prove that at the end of the above two operations carried out in order,the matrix retains the sorted order of its rows.
What is a reentrant function? how do you make a function non-reentrant?
2D Matrix(n * n) of positive and negative numbers is given. Matrix is sorted rowwise and columnwise. You have to return the count of -ve numbers in most optimal way.
Do Postorder traversal without using recursion.
Binary Tree Node has left, right and next pointers. Create a linked lists at each level connecting next pointers at each level.
Binary Search Tree Node has left, right and next pointers. Populate next pointers such that all nodes are connected in sorted order through next pointer.
Consider an array of positive and negative integers. We want to
find a slice of this array (i.e. a sub‐array of consecutive elements) with at least two
elements, such that the sum of the elements in this slice is equal to 0. The size of the
slice can be anything (i.e. from 2 up to the length of the original array), and we don't
care about finding the first, last, shortest, or longest slice, we just want a slice.
Example: from [2,3,-1,2,-4] we would like to find the slice [3,-1,2,-4], where 3 + (-1) + 2 + (‐4) = 0
Generate all subsets of a given set. In another words generate super set of a given set. Example- Given set {1,2,3}. Output- {}, {1}, {2}, {3}, {1,2}, {1,3}, {2,3}, {1,2,3}
n person in the town. for every pair of person (A, B), A either likes B or dislike him. If this town has a election, the leader should be liked by everyone and he does not like anyone? how would choose? what is the best performance of algorithm?
How to categorize web pages by its languages?
If using dictionary, what kind of data structure would be best?
Given a list 2 36 5 21 8 13 11 20 5 4 1. Divide it three sublists - one of numbers <5 , 2 of numbers == 5 if duplicates. third having numbers > 5. This should take linear time, shd be inplace. The three lists need not have to be sorted.
A calculator with only ":=" and "x". Given a and n, find the smallest number of multiplications to compute b=a^n
Exp:compute a^6 b1:=a
b2:=b1 x b1
b3:=b2 x b2
b4:=b3 x b2
Create two evenly balanced teams for a game of soccer.
Condition:The difference between the number of players in both teams should not differ by more than 1 . Each player has skillpoint associated with him. The total skill point of the players on each team should be as nearly equal as possible.
How will you implement multiplication and division without using "*" or "/" operator?
What happens when the method is called? Explain
public int normal(){
try{
return 10;
}finally{
return 20;
}
}Return count from an integer array of size 15 when the sum of sub array is 25
#include<stdio.h>
int main()
{
int a=10;
switch(a)
{
case '1':
printf("ONE\n");
break;
case '2':
printf("TWO\n");
break;
defa1ut:
printf("NONE\n");
}
return 0;
}
What will be the output and why ??
class a
{
public static void main(String args[])
{
c B=new c();
gen(B);
System.out.println(B.B1[0].x);
}
static void gen(c C1)
{
C1.B1[0].x=5;//bug in the line
C1.B1[1].x=6;
C1.B1[2].x=7;
}
}
class b
{
int x;
}
class c
{
b B1[]=new b[3];
}
there is a bug as shown in above program ?what is that bug? solve the bug?(program is in java language)
You will be asked to select the figure disimilar to others, ALL are pentagons except one is Hexagon
If a person sells 65% of his property, total property being 10,222 worth, how much he still owe (similar question)
if a clock looses 2 secs per day, how much time will it loose in 2 days ?
If one coin is not a dime in 15 cents out of the two, what are the two coins
For Onsite Call: Epic will give you 10 questions to be done in 2 mins, 15 logical questions, and 20 questions related to MIIS programming language.
PLEASE NOTE, they hardly change the paper, so prepare these questions and expect them........
2 mins questions:
1) Vocation:Occupation
a) they are quite similar
b) they are quite opposite
c) not related
Explain the last job you had, as it was very close to this one.
What is the best way to handle distributed databases and to merge their results ??
implement the pre-order traversal of a tree.
If an application is running, but it does not produce output; memory utilization is constant, cpu utilization goes down to 0; what will be the problem.
what is left outer join.
In a clock, calculate the angle between hour and minute handle
Implement a connection pool
Design a game: which transform a word to a target word. for example: from head to tail, each step, you just can replace one character, and the word must be valid.
implement atoi()
Design a Crossroad signal system
Check whether a binary tree is BST(if the binary tree is very large, you can not simply in-order print all the nodes out.)
An array of integer of size N, all the elements are from range[1,N-1], one is duplicate, find it.
An array of integer of size N-1, all the elements are from range[1,N], one is missing, find it.
Given a singly linked-list, and a pointer to node, how to delete the node.
Fibonacci sequence and optimization
Design a file system
check a number whether is Power of 2
How to check singly linked list is a circular linked list.
An array of integers, only one integer appears odd times, all others appear even times, find it
class a
{
public static void main(String args[])
{
c B=new c();
gen(B);
System.out.println(B.B1[0].x);
}
static void gen(c C1)
{
C1.B1[0].x=5;
C1.B1[1].x=6;
C1.B1[2].x=7;
}
}
class b
{
int x;
}
class c
{
b B1[]=new b[3];
}
solve the bug in java
1.
2.
3.
4.Check whether a binary tree is BST(if the binary tree is very large, you can not simply in-order print all the nodes out.)
5.Design a Crossroad signal system
6.implement atoi()
7.Pattern Matching, if '.' is used as a wildcard, which means '.'can represent any character.
8.Design a game: which transform a word to a target word. for example: from head to tail, each step, you just can replace one character, and the word must be valid.
9.Implement a connection pool
10.In a clock, calculate the angle between hour and minute handle
11.what is left outer join.
12.If an application is running, but it does not produce output; memory utilization is constant, cpu utilization goes down to 0; what will be the problem.
13.BST over hashtable
14.implement the pre-order traversal of a tree.
15.Given a singly linked-list, and a pointer to node, how to delete the node.
16.File external sorting.
Given an array of integer and a target number. please find out two number that add up to the target.
Calculate the Depth of Binary Tree
Given a range 0-N, generate 'M' random numbers from the range without any duplication. The space complexity is O(1).
Given a sorted list of integers, ie. { 1, 2, 3, 3, 3, 3, 4, 5, 6, 7, 8, 8, 8, 9 }, write a program that prompts the user to input an integer and the output should give two things:
1. The index of the first occurrence of the integer.
2. The number of times the integer occurs in the list.
For instance, if user inputs "3", then the index of first occurrence is 2 and the number of occurrences is 4.
Hint: The algorithm should scale well with large arrays of sorted integers so a linear search is not the best option.
Given an integer number X find those integers A and B that:
A^B = X (^ means power)
A and B may be from 0 to 1000.
You may assume that for each given X, A and B really exist and they're really integers [0,1000].
Write a function which gives a hint/suggestion for the (i,j) position in a sudoku?
design a voice conferencing system
Can you serialze the following class
public class{
String st='mansoor-shaikh';
String int = 90;
Thread myThread;
}
Explain why and why not?
How will you handle multhithreading issues in Servlets
public MyServlet extends httpServelt}
private String = 'jackass-gorenberg'
private int counter=0;
doget(){
dopost()
service(){
//now access these global variables
}
}
Can you override service() method, and what you do when you access variables in service method, with respect to global variables
Write Java code to reverse a
char[] ar = {'A','R','G','E','N','T','I','N','A'}
without using any other array or creating objects
Given a binary tree, how would you join the nodes at each level, left to right.
Say there are 5 nodes at level three, link all of them from left to right.
Compare the following 2 functions:
function concat1(a, b) {
return a + b;
}
function concat2(a, b) {
return a.concat(b);
}
Design a ER model for university system? consider you are designing a db that will be hosted by us and any university can use it and we will host the database for them. design in such a way that we do not have separate db for each univ? etc. etc.
Least common ancestor of a binary tree, BST ? complexity ?
Design a logging system for an application server? see to it that Logging system you define does not include a large overhead in case of large loads to server ?
Write an algorithm to check the winning condition in a tic-tac toe game for a NXN grid ? (Hint . can be done in O(1) need int ROW[N]; int COL[N]; int diagonal; int anti-diagonal )
Which data structure will you use to store large number of integers? How will you find the median ? (Hint: B-tree , same as bst store number of nodes of subtrees)
Write an algorithm to find the median in a binary search tree? (Hint: Store the number of nodes in left subtree and right subtree and use k-selection algorithm CLR)
Is it possible to use try without catch in java
Given two arrays A [1..n] and B[1..m], find the smallest window in A that co
ntains all elements of B. That is, find a pair <l,k> such that A[l..k] conta
ins B[1..m]
For example, given A = 3,1,5,7,3,5,2 and B = 5,3 then the smallest window is
[3,5].
any efficient way to do that?
implement a circular queue class, note it will not overflow (my understanding is if the capacity is reached, the enqueue function should return false).
How would you test it?
describe the layers of windows system
What is one feature or features missing in current windows system?
How does communication take place when we write yahoo.com in our browser and web server.He asked me to explain each and every step.Can you guys please help me out with this question?till now no interviewer is satisfied with my answer :(
there is function which produces a float number between 0 and 1 till 16 places.I was supposed to make random integer number generator.
Write a function that takes an input string and returns a new string containing the unique characters from the input string, in the order in which they appeared in the original string. For example, "This is a string." should return "This atrng.". Show how you would test this function.
Write classes you need to support validation of inputs and return values. Show what specific input values and return values you would use to validate it.
C:\>ping.exe /?
Usage: ping [-t] [-a] [-n count] [-l size] [-f] [-i TTL] [-v TOS]
[-r count] [-s count] [[-j host-list] | [-k host-list]]
[-w timeout] [-R] [-S srcaddr] [-4] [-6] target_name
Given a 32-bit binary number, what is the quickest way to find the position of the most significant 1 bit?
Given a sequence of ascending integers that start at 1 and one integer is missing from the sequence, what is the quickest way to find the missing integer?
Given a cube of dimensions 10 x 10 x 10, if the outer layer is stripped off, how many units remain?
#include<stdio.h>
#define TOTAL_ELEMENTS (sizeof(array) / sizeof(array[0]))
int array[] = {23,34,12,17,204,99,16};
int main()
{
int d;
for(d=-1;d <= (TOTAL_ELEMENTS-2);d++)
printf("%d\n",array[d+1]);
return 0;
}
what is wrong ??
How will you dynamically allocate 2D array? Use 2 malloc and then do the same thing using only 1 malloc.
Design a TV remote control for children less than 6 years old.
Write a function to generate all possible n pairs of balanced parentheses. For example, if n=1
{}
for n=2
{}{}
{{}}
Program 2: Implement an elevator system
Program 1: Find the number with highest frequency in an array.
In a telephonic interview:
1. Advantages and disadvantages of recursions
2. Comparison of BT and BST
3. BFS and DFS - advantages and disadvantages
4. how to detect a loop using DFS
5. shortes path algorithm
Did you use any Maven repository like nexus? How Maven is better than ANT
How inheritance works in Hibernate, for example 1. Map one table per concrete class. explain all
Generate a random number for SSN i,e int of xxx-xx-xxxx (9 digits), then write a function that checks if xxx and xx and xxxx and the total xxx-xx-xxxx is a prime number and return true or false. What is the complexity of the algorithm?
boggle solver problem: given a NxN matrix of letters, print all the valid words. You can make assumption on the dictionary to support hasPrefix, isWord etc. How would u write the recursive function in order to search word efficiently?
#include<stdio.h>
#define FUN(x,y) x##y
int main()
{
int val1=10;
int val2=20;
printf("%d\n",FUN(val1,val2));
return 0;
}
what is the output of the program?
How to find minOfStack()in O(1). restriction is: pop()and push() should be in O(1) only.
Write a code to clear nth bit in an integer.
Write a code to reverse words in a sentence of words. for ex: I am a boy --> boy a am I.
scope of x,y,p,q and where respective variables are stored.
static int x;
int y;
void foo()
{
static int p;
int q;
}
What is the use of volatile keyword in C?Gave a standard answer,asked to elaborate more.Don't know how.
How is concurrency handled in operating systems?Difference between Mutex and Semaphores in context of threads and processes.
how would u implement mutex?
how would you design a parking lot?
find most often seen string from a log file
struct node{
struct node* next;
struct node* reference;
}
duplicate the list by:
struct node* duplicate(struct node* original)
how to handle the "reference" in the new list?
class A1 {
public:
int upper;
int lower;
A1( int i ) : lower( i ), upper( lower+1 ) { };
};
what is wrong with the above code?
class A {
// ...
};
class B : public A {
// ...
};
void fct( A a ) { /* ... */ };
int main() {
B b;
fct( b );
};
what could be the errors because of this code?
You are given two arrays
int Array1[n], Array2[n];
Each array contains numbers which are half even and half odd. Write C code that will return two arrays one having only even numbers and other having only odd numbers. You are not allowed to use additional data structures like hash,array etc but can use temp variables. The solution should have O(n) complexity.
You have a database which catalogs all the buildings in NY. You decide to use a 4 byte integer value as unique identifier for the table. Will it work ?
(The answer would reduce to finding number of buildings in NY)
What types of data structures can you use for Look ups? If you have an associative array A with index "hello". How is A["hello"] actually evaluated , as in how does system map to a memory location using index "hello"
You are given N blocks of height 1…N. In how many ways can you arrange these blocks in a row such that when viewed from left you see only L blocks (rest are hidden by taller blocks) and when seen from right you see only R blocks? Example given N=3, L=2, R=1 there is only one arrangement {2, 1, 3} while for N=3, L=2, R=2 there are two ways {1, 3, 2} and {2, 3, 1}.
Each leaf node has a boolean value associated with it, 1 or 0. In addition, each interior node has either an "AND" or an "OR" gate associated with it. The value of an "AND" gate node is given by the logical AND of its two children's values. The value of an "OR" gate likewise is given by the logical OR of its two children's values. The value of all of the leaf nodes will be given as input so that the value of all nodes can be calculated up the tree.
It's easy to find the actual value at the root using level order traversal and a stack(internal if used recursion).
Given V as the desired result i.e we want the value calculated at the root to be V(0 or 1) what is the minimum number of gates flip i.e. AND to OR or OR to AND be required at internal nodes to achieve that?
Also for each internal node you have boolean associated which tells whether the node can be flipped or not. You are not supposed to flip a non flippable internal node.
Given an array of 'n' random integers. Given an integer 1<=n. Find the k numbers such that the minimum difference of all the possible pairs of k numbers is maximum (maximum among other minimum differences for various possible selections of k numbers ).
Connect the leafs in a binary tree and return a reference to the first of the linked leafs. This would allow clients of this API to subsequently traverse the leafs. The API has a fLR flag indicating if the leafs should be connected from left-right (fLR = true) or from right-left (fLR = false).
Please implement the following API:
public Node ConnectLeafs(Node root, bool fLR)
Parameters:
Node root – a reference to the root of the tree
bool fLR – direction of leaf liking.
Write a function for the following scenario:
Given a number determine wether the number is sum of consecutive positive integers,if it is not return false else return true. conscutive integers can be from 2 to n
How will you convert an unsigned int into base
Given a file with a lot of words (10 million) find out the top 10% most frequently occuring words
a) Design a data structure to store an arbitrarily large number
b) How will you use it to store two such number and add them.
c) Write down the class (code) for the data structure.
What is the difference between hashtable and encryption.
Note: These questions were asked just to screen out non-eligible candidates and not during any phone interview or at onsite(are u kidding me :))
Given a string "amazon.com", print the alphabet in the string with their respective counts.
ex: a-2, m-1, o-2 etc.
Note: These questions were asked just to screen out non-eligible candidates and not during any phone interview or at onsite(are u kidding me :))
It was asked in telephonic interview
u have stream of infinite no of integers and a function named getnext() which gives the next integer from stream continuously.U have to store the numbers in decreasing order and remove duplicate also in efficient manner.
Write code to find the duplicates in an array
What happens when you type http://xyz.com
and questions related to that like http requests ,ports , sockets etc
He explained a system which had
1. A queue
2. A processor which would read the data from the queue and write the data into files.. 24 files..one file for each hour in the day
3. A logger which would read these files and write into the database
Write test cases for this system
About performance testing –
the tool you used…Explain the tool..explain how you used the tool..
What are the parameters monitored..What results are captured
What is response time..etc
Write code to get the mirror image of a tree ( the same tree needs to be modified to get its mirror image)
Given a string “aaabbcccc…..” . Convert it into the form “a3b2c4….”
What are the test cases? What are the cases where your written code will fail?
Write a program to convert a number into roman numerals.
What is the difference between class members and instance members?
There is an array of odd and even numbers. Now, sort them in such a way that the top portion of the array contains odd numbers, bottom portion contains even numbers. The odd numbers are to be sorted in descending order and the even numbers in ascending order. You are not allowed to use any extra array and it has to use a conventional sorting mechanism and should not do any pre or post processing.
find the common node in two singly LL.
Given a BST and sum,find minimum node from root to leaf till u get the sum of node values equal to that sum.
Fastest way to multiply by 7?
Given 8 cue balls , one is weighing lesser than other 7. Find that(light weight) ball using just 2 chances on balance weight.
What is the difference between hash table and binary search tree? Give an example that we prefer to use binary search tree rather than hash table.
Assume you have two sorted integer arrays. How can you find the intersect of these two arrays? (Hint by asking question: assume that these two arrays can contain duplicated integers, and they do not have the same length) What is the time complexity? Write a function to implement it as follows:
void intersect(int *a, int *b, int la, int lb)A user wants a software to design logic circuits. This cloud of logic circuit has several inputs, and one output. What data structure will you use to design such a cloud?(Hint by asking question: You can use any kind of basic gates, AND, OR, NOT etc., but these gates all have two inputs and one output). Write out the code to define this data structure. How does the data structure store the input? How do you get the final output? Write a function to generate the final output assuming that the input has already been stored in this data structure.
implement complex lock ? One thread has access to lock and other threads who wants to access the lock sleeps
Implement Memcpy
Given an array of n numbers in which all the members are less than or equal to k (k<n). device an algorithm of order O(k) to find the first repeating element.
what is memory dump? what are the uses of memory dump?
implementation of malloc()
Types of kernel, what are the advantages of one over other?
write a program to reverse the words of a sentence
Ex- my name is abc---> abc is name my
Given the head pointer of the linked list and the data of the node to be deleted.just delete that node...your program should check for all possibiltie
differnece b/w executable and object file ?
how round robin scheduling is implemented?
sometimes OS crashes..why does it happen??
System calls, how they works? how we move from User mode to kernel mode?
how free() knows, how much memory it has to deallocate?
Implement a Stack in that push(),pop() and max() can be done in O(1) time...stack should be implemented using linked list and max() should return the node(not the value) containing max value
find all denomination for a give amount for ATM in C language eg: say x=1000*x1+500*x2+...+1(paise)*xn than find x1,x2,...xn
try to separate x into maximum no. of denomination.
The code should be in C language.
an array of 0 and 1 in random order
segregate 0 on left and 1 on right in 0(n)
What is your salary expectation?
How to increase web browsing speed. You are allowed to do anything at client/server
Implement merge sort of linked list
A program works fine in debug_build but crashes in release build. why?
Write code to compare two arrays if they contain the same elements
Given a url how do u download page from server. He was looking for some command to do that in windows when I mentioned u can use wget in linux. How do u get all pages of that url. How do u eliminate cycles and same pages?
Write a Class describing Singleton pattern
how to implement a queue using one integer. this should store value 0 to 9. example suppose queue has first value 2 then insert 4 then 6 so it should look like 246. first value should be popped as 2. then it should be 46. program should support 0 in all the levels also. example queue should handle like 01235 also, 0 as first value in queue. remember 0 just to use integer, nothing else as data storage.
Write code to convert a hex string to a byte buffer
Given a binary tree
struct node{
struct node* leftChild;
struct node* rightChild;
struct node* nextRight;
}
populate the nextRight pointers in each node.
What are hash tables? What is collision ? How can collision be resolved (He asked me all the methods and still wanted some more :P )?
When should a Hash table be used and when should a BST?
Do Hash Tables always give constant time 'find' complexity? If yes, why would I ever prefer to use BST over Hash table ?
Design an algorithm to count number for Bit 1s in byte
Write C Code for Fibonacci Series. Write both the Iterative and Recursive implementation.
In mxn matrix if you find 0 in an element make all elements in that row and column to 0?
Write a function to convert a given float values into string without using toString function?
(E.g) I/P 2.34 O/P "2.34"
You r given a large string of characters lets call it Sbig. Then there is a small set of characters lets call it Ssmall. You have to find smallest substring of Sbig which contains all characters in Ssmall.
For example you are given Sbig = "hello what are you doing"
Ssmall= "eo"
answer is "ello"
Merge 2 sorted arrays in constant space and minimum time complexity
Given a file with millions of lines of data. 2 lines are identical, rest all are unique. Each line is so long that it may not even fit in memory. What is the most efficient solution for finding the identical lines?
Convert in O(n) time:
a1a2a3a4.....aNb1b2b3b4.....bN
to
a1b2a2b2a3b3a4b4..........aNbN
given an array of positive and negative integers. Find the pair of number whose sum is closer to zero.
Find the next in order node of given node in binary tree. Write the program of same. pointer to parent node is given.
Given a positive integer having all unique digits. Find the immediate next greater number having the same digits.
Consider a complete 'tree'. Find an equality relation between number of internal nodes and external nodes (leaf nodes) in that tree. He started with a binary tree and then extended this question further to 'n'ary tree.
You are given 2 arrays of size 'n' each. You need to stable-merge these arrays such that in the new array sum of product of consecutive elements is maximized.
eg
A= { 2, 1, 3}
B= { 3, 7, 9}
Stable merging A and B will give an array C with '2n' elements say C={c1, c2, c3, c4, c5, c6}
You need to find a new array C by merging (stable) A and B such that sum= c1*c2 + c3*c4 + c5* c6..... n terms is maximum.
Give some important differences between threads and processes.
When should I use thread and when should I use processes?
You are given a single processor. Will it be still beneficial if I use threads to parallelize my work? Explain with reasons. If yes, give me a case.
How is heap different from a BST?
When should I use heap and when should I use BST?
What are hash tables? What is collision ?
Given 2 sorted arrays A and B, sorted in increasing order, find the minimum value of |A[i]-B[j]| for all i belonging to A and all j belonging to B. Preffered order O(M+n) in the worst case. m being size of array A and n being size of array B.
Then he extended the same question to n sorted arrays with k elements each. I was required to find the minimum range in which the values fall.
He gave me an array of Integers, each integer allows me to make at max its value jumps. If i am at zero, i'm stuck i cannot move forword. He asked me to find,
1). If the last index was reachable from the first index.
2). Minimum number of jumps required to reach the last index, given any index as the starting index.
3). Total number of ways one can reach the last index.
I was asked to write a code for this.
ex: 1 3 5 8 9 2 6 7 6 8 9
initially at one i can make only one jump to 3, from 3 i can jump either 1 step reaching 5, or 2 steps reaching 8, or 3 steps reaching 9. Carrying on in the same way till i can hit the last index.
A binary tree is given with a positive weight attached to each node. Find the subset of nodes in the tree whose sum give you the maximum weight such that if a node is in the subset, none of its children can be in that subset.
gh
fg
Design and implement car parking service in which charge is based on time duration in parking.
Given an array of integer which is very large and can not be loaded in the memory. Search top n integer in this.
You are given m*n two dimensional integer array. value in each row and column is sorted (you may assume ascending order). Search the all location of given number.
Product kindle. User registers with and a corresponding email address is generated. How would you design a system to generate this email (unique for every user)
2. why need virtual function in C++?
1. compare the advantage and disadvange of BST and hash
What's the difference between system calls and library functions?
For those candidates who know SQL: There is a table with
gene_ids ('gid') and clone_ids ('cid'). Each gene only resides on a
single clone and each clone may contain multiple genes. How do would
you find how many genes are on each and every clone? Please provide the
SQL.
50 char *b, q, *r;
200 b = getbuf ();
201 q = *b;
212 R = anotherfunction (b);
213-2003 /* we want to use 'q' and 'r' here */
2000 char * getbuf ()
2001 {
2002 char buff [8];
2003-2050 /* unspecified buff defined here */
2051 return (char*) buff;
2052 }
1. What will be in variable 'q' after line 201 is executed? Under
what conditions might this not be so?
2. Is there an alternative, but equivalent, way to write line
2000? If so, what is it?
3. Is getbuf() a reasonable function?
4. Will getbuf() execute at all?
5. Please comment on line 2051.
6. Is getbuf() good practice, and why?
7. What line not given should be provided for compilation?
8. How, exactly, could one get a second 'char*' to use back from
this function? Be specific in terms of the exact syntax needed. (That
is, provide code.) Another way to state this question is how can this
function be modified to return a 'char*' (that is, it maintains the
same return type) from the function, and an additional 'char *' value
in one function call. Please make sure that your answer will work even
if the size of the char * desired is not known in the outside calling
function. Avoid (do no use) C++ syntax. Include statement in called and
calling functions. Use food programming practice.
Can Java constructor has private or protected access type?
If you want to implement a class includes firstname and lastname, then implement equals() and hashcode()
Talk about collection framework of Java.
What will happen if we add the same object to the Set?
Given one million integers, find a solution(data structure and algorithm)to find an integer inside.
Design a multimedia cookbook
which software do you hate and why?
a monochromatic screen is represented using single dimentional array. write a code to turn (x,y) pixel on.
Repeated question: write code for aligned malloc and free.
A dictionary is given. You have a word which may be misspelled. How will you check if it is misspelled?
How to reverse an integer. What if it is a -ve or +ve number?
How to design the netflix movie recommendation algorithm?
Give two parking locations P1 and P2, P1 and P2 both have n slots. n-1 cars with same IDs are parked in n-1 slots in both P1 and P2. Design an algorithm to let n-1 cars in P1 and P2 park in the same slots
Discussed about external sorting, priority queues, hashing etc
given a number round it off to next power of 2.
eg: if given 3 it should return 4,
if given 5 it should return 8.
Given a binary tree and a sum , return true if the tree has a "root to leaf" path such that adding up all the values along the path equals the given sum.
Return false if there is no path.
Give the algorithm to multiply large matrixs on system with very less memory which can not hold even one coll or one row.
You have a collection of marbles of different colors.U have many boxes with u which contain marbles of the same color.Ur younger brother has played with the marbles and scattered them randomly.Write an algorithm to arrange the marbles in the boxes in such a way that each box contains the marbles of the same color.The algo should be optimum in time and space respectively.
You have 240 barrels of wine, one of which has been poisoned. After drinking the poisoned wine, one dies within 24 hours. You have 5 slaves whom you are willing to sacrifice in order to determine which barrel contains the poisoned wine. How do you achieve this in 48 hours?
Given a set of points, find the line that intersects the most number of points
Explain the functionality of malloc...If a pointer ptr is pointing to array of 100 bytes and free(ptr) is called..then How the compiler knows that 100 bytes are to be removed...Explain any other way to optimize this.
Our cell phones have T9 dictionary embedded for message writing...How this dictionary is implemented? State any other way to optimize complexity.Mechanism of Addition of new words in that dictionary.
What is metadata? What is the difference between data, meta data and information?
Difference between Use case and Requirements Specifications?
Write a program to reverse a string using recursion?
Given an array of integers(both positive and negative) divide the array into two parts(sub-arrays) such that the difference between the sum of elements in each array is minimum????
write a program to shuffle an pack of cards in the most efficient way.
sort an array of 0's and 1's in a most efficient way.
Given a road containing k lanes. A frog at one end of road needs to cross the road, but it can jump only to middle of a lane, in time d i.e. jumps to middle of first lane in d, then to middle of second in 2d and so on. you are given data of cars in each lane, 1km before the point of frog. All cars are travelling at constant speed. Given functions jump and wait, design algo to help the frog cross the road. (the frog can only jump fwd, not back)
how to find loop in a linked list other than the following ways
1. fast/slow pointer
2. visited flag
3. storing address and checking against it
What is groupby?
Find the FIRST non-repeating character in a string.
Ans: I gave the hash function solution, but interviewer wanted a O(1) space complexity and O(n) runtime complexity.
So any other solution with O(1) ?
If I have 2 pointers A pointing to B and B pointing to A. Is it an error?
Explain the difference between calloc and malloc
About databases : primary keys, composite keys, table joins , relations
About Junit. If I have 2 test cases A and B where A depends on B then how wil I run these test cases using Junit
Was asked to write a program to solve a given equation. Write the test cases
Write a program to remove the duplicates from a list of integers . Write the test cases
Write code for binary search
Consider a moblie phone : when you save the number, the number gets saved under a different name . What is the priority and severity of the bug
What is the most critical bug you found
Explain bug life cycle
What is the difference between retesting and regression testing
What is the difference between a bug and a defect
How are function calls implemented? What are the parameters that are stored on the stack when a function is called?
What are Http Headers
Test cases for LRU cache
What is performance testing..How would you test the performance of a flash object
Given a function that returns a random number between 1 and 5, make it return a number between 1 to 7
Find the intersection of 2 sorted arrays.
Give all test cases to test
Given an array of numbers, write a function which will return another array containing the elements of the previous array but in random order.
How would you test a general website login page.
Code and write test cases for compare(string str1, string str2).
Given a set of coordinates (x_i, y_i), i ranges from 1 to n, the coordinate values are integers, write a function 'bool isCenterInteger(int points[][])' which returns true if at least one of the midpoints of the line joining the points is an integer.
Convert a binary search tree to a sorted doubly linked list
inplace.
implement factorial, do remeber to handle the overflow case, which is actually the key point, otherwise this problem will be too simple
given a matrix (assume it is a bitmap), print all cells that are on
given a string, print each character and its number of occurence in sequence. use BST and no recursion, no extra memory is allowed.
e.g, char* str="bcdaceffbe", you should print
a 1 b 2 c 2 d 1 e2 f 2.
Write code to draw a circle.
Out of all the questions, MS asked me to implement a Reader writer lock problem.
And obv., I did get it but not full proof!
Try to come up with a robust code/solution.
You have a string of words (with spaces in it).
You also are given a character (say c).
Remove all the words in the string if those words start with 'c'.
e.g. "HELLO WORLD HAT" and say c='H'
then result should be "WORLD"
A man wants to grow tree very quickly. He bought some special tree seeds that double in height everyday. On the 10th day, the tree is 40 feets high. On what day was it five feets high?
Write a function to e reverse the order of words in a sentence using constant extra space
eg: "Here I am" would be "am I Here".
I tried to solve this problem by taking the space as delimiter and inserting each word rfrom the string into a stringbuffer.
sb.insert(0,word)
Finally the stringbuffer would have the reversed string.
But this does not satisfy the constant extra space condition as the size of stringbuffer is still dependant on string size.
Please write your inputs on this
The LL is in alternating ascending and descendin orders. Sort the list efficiently
egs: 1->2->3->12->11->2->10->6->NULL
. 10
6 12
4 -> 5 <-------->11<-----> 13 <--
|_________________________________|
In the BST you have the leaf nodes connected to form a doubly LL. Given a node, identify its height
A linked list has a loop.
Find the kth node from the end of the loop.
For example:
head -> 1 -> 2-> 3-> 4-> 5
|_______|
Find the 2nd node from the end of the loop which is node 5.
Find the maximum subsequence sum of an array of integers which contains both positive and negative numbers and return the starting and ending indices within the array.
For example:
int array[] = {1, -2, -3, 4, 5, 7, -6}
The max subsquence sum is 4+5+7= 16 and start index is at 3 and end index is at 5.
You have one dice.
If I roll a 1, I win.
If you roll a 6, you win.
What is the probability that you will win?
A client is deploying a web service from a server. The web service is slow. What would you do to find the root cause of the slowness?
given 2 dates, find if the 2 dates are a month apart, more than a month apart, less than a month apart.
I asked him to define "month apart"
He said, same day but previous or next month.
Given a log file, which contains a series of websites, which the user has visited, find the most frequent path of 3 websites.
e.g: If this is a log file
A B C D E
A C D B E
C D E B A
A C D E B
C D E A B
clearly, C D E in the most frequent website?
First I said graph, then I said hash table. Hash every 3 consecutive web sites and increment in Hash Table. Parse through HT and keep a variable which stores the max value you get the answer.
There are two nodes given in a tree(not binary tree). Find wether one node is parent/grand parent of other.
order should be O(1)
find pythagorean triplets in an array in O(N)
What is a time you failed or caused a problem that impacted coworkers or customers?
What is a bad online buying expierience?
Table CustomerOrder, columns customerid, orderid, orderdate.
Give a query for customers that placed orders today
Query to get the day in the last 30 days with the most orders
What is an index?
Why not add an index to all the columns?
What data structure to store index data?
Why a btree?
* Employees
o id
o name
o department_id
o start_date
o salary
* Departments
o id
o department
get max salary
get all names and dept
get dept that spends most on salary:
Write a program/script to find a file in the current directory and sub-directories, tools like find and grep are missing.
There are 3 guys in a room, persons A, B and C. They are shown a box with 3 black hats and 2 white hats. They are all blindfolded and a random hat is placed on each head. Person A's blindfold is removed and is asked which colour hat he has on - answer is "I don't know". Person B's blindfold is removed and he gives the same answer. Person C answers, without having their blindfold removed, the colour of their hat and they are correct. What colour is person C wearing, and how did he know?
You have two ropes of equal length and an unlimited supply of matches. The ropes each take 60 minutes to burn, but do not burn uniformly (ie it does not necessarily take 30 minutes to burn half the rope). How do you use the ropes and matches to time 45 minutes?
A gold bar is in 7 segments and you need to cut off a segment and pay a member of staff every day. At the end of each day, they must have one more gold segment than they had the previous day. How do you issue 7 segments over 7 days with the fewest amount of cuts?
Given an array of any length holding integers (a buffer of bytes), write an algorithm to return the first unique element (ie not repeated in rest of the array).
how do you come to know what method in java is slow / has bad performance. how will you use the profiling tools for it?
array having 50 values. 2 values are missing. can u do it better than multiplication and addition method .
write a Macro which when given an array willl return the array size
Input: Many strings with alpha numeric numbers and integers
eg: String1= a,b,c,d,1,0,d,2,0]
Output: Integers with ascending order =
[10,20] ( concatenate 1 and 0, 2 and 0]
Write a code for this in any language of your choice [ time given 15 mins ]
Given an n X n array with rows sorted and cols sorted, find the number of negative elements in most efficient way
Is static constuctor exist in C++?
Removed due to signed agreement for non-disclosure of proprietary information.
How can we traverse through all the files in a folder and the subfolders. What system calls should be used(in C).
int main()
{
int n = 12;std::cin >> std::hex >> n;std::cout << std::setprecision(2) <<n;return 0;}
What would be the output given input is 12?
choice a:
12
choice b:
12.00
choice c:
18
choice d:
18.00
choice e:
1.80e+001
class A {};
void foo()
{
throw new A;}
Which of the following catch statement is valid?
choice a:
catch (A && e)
choice b:
catch (A e)
choice c:
catch (A * e)
choice d:
catch (A ** e)
choice e:
catch (A & e)
How would you find the Common elements from 2 Arrays which my or may not be of the same size?
You have 4 bottles each containing pills that weigh 10 grams each and 1 bottle containing pills that weigh 9 grams each, How would you find out the lighter of the 5 bottles by using a Digital Scale just Once?
Hint: He asked to open the bottles and take the pills out, and also grouping them wont work.
Write a function to reverse the words in a string (“cat and dog” becomes “tac dna god”). Please do not use any string manipulation functions that you do not implement yourself.
Write a function that receives three integer inputs for the lengths of the sides of a triangle and returns one of four values to determine the triangle type.
1. Scalene
2. Isosceles
3. Equilateral
4. Error
Write a function that would return the 5th element from the tail (or end) of a singly linked list of integers, in one pass, and then provide a set of test cases against that function (please do not use any list manipulation functions that you do not implement yourself).
What is the difference between functors, call back functions and function pointers?
Write the code for a program that takes in the infix and the prefix traversal as an array and generate the postfix traversal as another array
we know how to FIX the loop in a linked list using that two pointers trick. Interviewer asked me to give proof for this.
how to do a spell checking program and give suggestion to possible correct spelling?
give you a set of points and a 3-D matrix;identify if any comb in the set is equal to the square plane.
how to implement it?
and the lowest complexity?
In our indexes, we have millions of URLs each of which has a link to some page contents, that is, URL->contents. Now, suppose a user types a query with wild cards *, which represent 0 or multiple occurrences of any characters, how do you build the indexes such that such a type of query can be executed efficiently by finding all corresponding URLs->contents efficiently. For example, given a query http://www.*o*ve*ou.com. You need to find iloveyou.com, itveabcu.com, etc. I got stuck for this problem during my interview even though I got all of other problems solved. Let me list a few things that I have tried, please help me with more efficient algorithms. Thanks a lot! This is not just for the interview any more, but for solving the interesting problem (at least I think so).
A few possible solutions proposed by me:
1) Using * to split the query into several words, for example, *o*ve*ou => o, ve, ou, and then search o, ve, ou separately and then combine the results,this seems a good way but I cannot figure out an efficient way. This may be more suitable to find pattern for a single URL, however, the problem here is for millions of URLs. We should avoid scanning all URLs.
2) Soring URLs? Not sure how to deal with wild cards then.
3) Suffix tree? Build a suffix tree for each URL, then for the partitioned words, search the suffix tree? But how? This also looks like a possible solution, but how? I did not figure it out.
4) Finally, when I tried all the above methods and did not please the interviewer, I asked him if I can use UNIX grep? He said definitely NO!
Ok, guys, please help me! This question is really tough for me. But maybe very easy for you guys! Please help!
Sort a huge list of numbers ,each of which is of a fixed size,in O(n)time
In a given binary tree,find the largest subtree that's also a BST.
Given a sentence reverse words of the sentence.
I am a fool
to
I ma a loof
How would you find out all the books purchased in Bangaalore on a given day.
Given a sentence containing anagrams, find the anagram pair and print it as <cat,tac> types
Given a Binary Tree(not a BST) find the maximum element.
"Simple Parallel Crypto"
We need a utility that will perform a simple XOR crypto transform. They key will be given as a set of bytes in an external file and the number of bytes in the key will dictate the "chunk size". The plain text data will be given on stdin and the utility must break it into chunk-size sections and XOR it against the key and write the cypher text it to stdout. After each chunk is processed the key is rotated left by one bit to make a new key. This means that the key will repeat every N chunks, where N is the number of bits in the key. The plain text may not be a multiple of the chunk size in length. The plain text may also be very large, far exceeding the available memory+swap space in the system.
In addition to just performing the algorithm, the utility needs to scale so that multiple chunks of plain text can be efficiently processed in parallel on multi-core/multi-CPU machines. As such, a number of threads must be created to process chunks of data concurrently. Regardless of the number of threads, the output cypher text must remain the same.
Any errors/status must come out on stderr.
Required Command Line Options:
-k <filename> Specify the key file
-n # Number of threads to create
Example:
The keyfile contains two bytes: 0xF0 0xF0
The plain text file has the bytes: 0x01 0x02 0x03 0x04 0x11 0x12 0x13 0x14
encrypt -k keyfile -n 1 < plain > cypher
The cypher text has the bytes: 0xF1 0xF2 0xE2 0xE5 0xD2 0xD1 0x94 0x93
Implementation Details/Notes:
The utility can be written in C/C++. If C/C++, it should build and run on a POSIX system (like Linux or Mac OS X). A good way to generate keyfiles and plain text files is as follows:
dd if=/dev/urandom of=plain bs=4096 count=4096
dd if=/dev/random of=keyfile bs=4096 count=1
How SpinkLocks work in SMP and UP architectures.
Addition of two signed characters, what happens the carry bit, and to the signed bit. Can the carry bit be over written on a signed bit?
Find number of friday 13th's from today to the end of 2012.
What is the most efficient way of representing a number in the multiple of 256? (Clue - How do you clear a bit?) - Anyone has an answer to this.
You are given a pointer that points to an array of elements. The elements could be int/float/string/char. Write a program to add/concatenate all the elements of the array.
Difference between Macro and inline?
Why static is not used to define global/local buffer?
write a program to print Fibonacci series?
what is the C++ equivalent of linked list?
Design n stacks using single array..
Array size is N
Design a data structure which has the following features
-> push the data
-> pops the last inserted data [LIFO]
-> Gives the minimum
All of the above operations should have a complexity of O(1)
Program solution for 'game of life' (3X's in an nXn grid. Initial stage - 3 x's horizontal next to each other. Next step - alternate to vertical 3 x's center one stays at the same position. Stages repeat. I coded using arrays, interviewer was interested in a solution without the use of arrays.
Write a function to add an array of numbers.
Assuming you have a web mapping service (e.g google map) that works perfectly well in USA. If you want it to work in other countries, what technical problems do you foresee?
A pretty open end question. One possible answer the interviewer gave was that the address system could be different.
Assuming you have 1 billion (or any arbitrary large number) files sitting in a machine. Given a phone number, how do you find files that have the number in it?
Rather than actually give him an algorithm, the interviewer was looking for some ideas.
Describe the entities of a blogging system like facebook
You are the MMU of your computer and have the flexibility of managing memory assignment at will i.e. dynamically..
Design a strategy to optimize the number of memory locations to be used for incoming data that will be resident in memory from time t0 to t1(the memory will be available after that).
The data to be resident will have its own residency time T(i) to T(j) in a particular time period and if a memory location is occupied, it can not be assigned to incoming data.
You can create memory location dynamically for incoming data and have to generate a strategy for optimizing this #. Incoming data can not wait.
Hi all
can someone here explain how iPhone testing is done in QTP?
Pls elaborate what software methodolgies used for iPhone testing?
How database testing done in mobile applications?
Thanx
Snigdha.
how is padding beneficial
Saw this question in one of the algo communities.
Amazon telephonic interview question on Matrix
Input is a matrix of size n x m of 0's and 1's. eg:
1 0 0 1
0 0 1 0
0 0 0 0
If a location has 1; make all the elements of that row and column = 1. eg
1 1 1 1
1 1 1 1
1 0 1 1
Solution should be with Time complexity = O(n*m) and space complexity = O(1)
how to find out the maximum disjoint-edge paths between two vertices s,t in a graph? Does your solution give maximum number of paths, validate?
Write a thread safe singleton class
Write a function to find the longest common sequence of leaf nodes among two binary trees. Optimize for time and space.
Write a function to print out only the leaves of a binary tree
Given an unsigned integer 1345, the program constructs a linked list of 1->3->4->5.
Write the test cases for it..
SQL: Retrieve second highest salary and the corresponding Employee Id from a Employee_Salary table.
Given two sorted arrays where the size of second array is large enough to hold the first array, write code to merge them (in sorted order). Write test cases
SQL: A table has only one column. Retrieve all the data which are different from their previous data.
Write code to check if a string contains a substring.
Peak Reduction Algorithm - Function receives an array of integeters and a separate integer to use as the amount to reduce the peaks of the array by equally to the next lowest peak(s) iteratively until that integer reaches zero.
could anyone please suggest an answer to this?
Balance factor of a node in a binary=(number of all its descendants/level of node);
balance factor of tree=sum of BF of all nodes
Find the balance factor of a binary tree in most efficient way.
Write a c code for multiplying 64 bits numbers using 32 bit processor.
array1 :4,1,6,2,8,9,5,3,2,9,8,4,6
array2 :6,1,2,9,8
second array contains elements which are in first array in consequetive locations but may be in any order.Find their starting and ending indexes in array1 most efficiently.
(Be careful of duplicate numbers).
He gave me an array of Integers, each integer allows me to make at max its value jumps. If i am at zero, i'm stuck i cannot move forword. He asked me to find the least selection to reach end of the array.
ex: 1 3 5 8 9 2 6 7 6 8 9
initially at one i have only make one jump to 3, from 3 i can jump either 1 step 0r 2 steps 0r 3 steps.
my solution is 1 to 3 to 8, 3 selection and i am done.
Device an algo for this
Write an algorithm to find out how many different summations you can compute using numbers range from 1 to 1000. 2 constrains
1) Each valid sum must be less than 10000
2) A number can only be used once for a sum
example:
1+2+300 < 10000 is valid
1+2+300+400 < 10000 is valid
1+2+2 is not valid (2 appear twice)
Write a class to represent a Very Big Integer (having an arbitrary number of digits, 1-infinite)
Write functions to implement the basic arithmetic on those Very Big Integers
How do you implement a 2D array dynamically in C? Get the row and coumn numbers as input from the user
given two binary search trees, merge them in O(n) time with O(1) space
What's the difference between assignment operator and copy constructor
What's the difference between pointer and reference
What are call back functions?
Write a C program that takes a string ( like "234") and returns the number ( 234)
Write the test cases for your program
how do you check for the large numbers (in C# how to prevent from having run time errors for large numbers)
Tell me something about your former internship
What courses are you planning to take in next year?
What is a functor?
Global and local variables - where are they defined. When should we use a local variable, a global variable. how do we optimize using these tactics.
Explain how communication happens between tasks in RTOS
Explain priority inversion in RTOS
how would you explain the "computer networks" to a Kindergarden child
Given a monochrome display in a one dimensional array, turn the lit on at the co-ordinates (x,y)
write a function to return a repeated two char in a given string? EX: FOOPARFOO here FO repeating twice and OO repeating twice. I told him o(n2) solution but he is looking best one.
C++ concepts:
Virtual functions
Exception Handling
Casts
Optimized way to find an element in a matrix where every row and column is sorted. (Hint: Interviewer expected sort of Binary search but in an optimized and intelligent way)
Find minimum number of characters that need to be inserted into a string (anywhere in the string) to make it a palindrome..(Hint: Interviewer expected a Dynamic Programming kind of solution)
n teams having different number of members, how will you seat them around a round table such that two person from the same team cannot sit next to each other.
Write an algorithm to find the number of six digit numbers where the sum of the first three digits is equal to the sum of the last three digits.
Given a variation of a binary tree(not BST) in which each node has a parent, left and right pointer. The nodes do not have any key elements or any other data to identify itself. The root is the node that has a null parent pointer. You are given the pointers to two random nodes in the tree which may or may not be at the same level. Find the first common ancestor to the two random nodes given in the tree.
given a string and mapping for each character ("abc", a->A1, A2
etc.) find all combinations possible, like A1bc, A2bc, A1B1c etc.
what is the difference between sysfs and /dev and when would each be useful
does declaring a global variable as a static have any affect on it from the point of view od accesibility
There is puzzle about finding the celebrity among the group of people. I was given the matrix NxN mentioning people who know each and who dont.
a b c d e
a 1 0 1 0 1
b 0 1 1 1 0
c 1 0 1 1 0
d 1 1 1 1 1
e 0 1 1 0 0Now in this case C is the celebrity. Need to find the algorithm for it O(N) and code it
BFS a binary tree but print the last row in reverse order.
Given set of data-points on a number line and their classification, find the best split point.
Find if a given integer is a power of 2.Optimize it.
in this function for inserting the link list why do u check for head==null and why not *head==null and whats the diff
insert(Node * head)
{
if(head==NULL)
return ;
...
}
Given 2 nodes in a binary tree, find their lowest common ancestor.
given an array of integers ( negative and positive ), how to you find the median ?
Write a function that takes an array of five integers, each of which is between 1 and 10, and returns the number of combinations of those integers that sum to 15. For example, calling the function with the array [1, 2, 3, 4, 5] should return 1, while calling it with [5, 5, 10, 2, 3] should return 4 (5 + 10, 5 + 10, 5 + 5 + 2 + 3, 10 + 2 + 3). You may assume that the input has already been validated. Show how you would test this function
Asking help to provide both recursive and non-recursive solution.
Give an algorithm to find whether 2 given strings are ANAGRAMS or not. Write test cases.
Have you ever called any device's function?
How would you reverse bits of an integer in an optimized way suitable for an embedded system?
How would you implement a mutex?
Write a function to shuffle cards
Design an on line poker room?
We have a stream of incoming numbers (say order#). how will you output the fist n smallest numbers. how will you store them?
ans:-here we will be taking a array of n size and in that we will be storing the first N number's.after that we will be checking every new number in array for wheather any greater t number present in array .if we get we will keep that in the position of the replaced number else we will skip that new number as this won't be in the list of small number's...
What are the disadvantages of using pointer?
how to count no of occurrence of a particular word in a given file of text. [c/c++] And if file is very large hw will u go about it.
Given a document and a query of K words, how do u find the smallest window that covers all the words at least once in that document? (given you know the inverted lists of all K words, that is, for each word, you have a list of all its occurrrences). This one is really hard. Could someone propose an algorithm in O(n)?
Given a character string, find out all the English words contained in the string. Optimize the solution.
I have a box full of red, blue and yellow balls. The probability of picking a red ball = probability of picking a blue ball = probability of picking a yellow ball = 1/3. The number of balls is large enough that picking one ball doesnt effect the probabilities. If I pick 3 balls at random from the bag, what is the probability that
a) I get all 3 red balls?
b) I get 1 red, 1 blue and 1 yellow ball?
A man has 3 kids. The product of the ages of the three kids is 36. How will you systematically list out the possible combination s for the ages of the kids, without repetition?
I had google interview today and i was asked to write my own vector class and implement functions like push_back and retrieve using index.. I did a very very bad job :-(
Find the median of 2 sorted arrays
Given 2 linked lists(which need not have unique elements) find intersection point in the form of Y.(it can be anywhere--middle or tail)
Hint: dont compare values, compare addresses
Given a custom function Rev(char *) eg: abc cde returns edc cba utilizing only this function convert
I/P: My name is tom
O/P: tom is name My
Given a array of 0's,1's and 2's arrange in a way that all 0's come first, then 1's then 2's.
ANS: Arrays.sort(array) (Java)
Basically, sort the elements in any prog lang.
Reverse a linked list. First I gave recursive. Then was asked for iterative.
Interview for Kindle in Amazon Chennai.
couple of questions on basic sql
1.get max salary of employees from each dept.
2. Find 3rd max sal of employees given a dept.
given an array of n elements, find if there is a subset of 3 elements sum up to value T with time complexity O(nlgn).
Why do we have main memory in our computers? Speed and Cost are never accepted answers.
Check whether the number is palindrome or not without using array?
Convert the 6 decimal system into 10 decimal system?
how to find the number of rotations in O(logn) complexity?
find the longest palindrome in a string?
How would you test the line function in paint?
Unix: You have 50,000 html files in a UNIX directory structure, some of which contain phone numbers in the format ***-***-****. How would you create a list of all the files which contain phone numbers? (Assume that you already have the regular expression)
1. What happens when exception is thrown from Destructor?
2. Memory layout of an object ( mainly how many bytes for an object with virtual functions ).
3. Finding a longest consecutive subsequence sum.
4. Finding a loop in a linked list
5. Finding the first non-repeating character in a string.
what r static functions in C
Given an array of integers where some numbers repeat 1 time, some numbers repeat 2 times and only one number repeats 3 times, how do you find the number that repeat 3 times.
I gave the hashmap solution. He was looking for a bitwise operator solution.
Given an array of 999 distinct integers ranging from 1 to 1000 including. Find which number is missing. Restrictions: loop over the array only once, can't allocate an additional array.
What data structure would you use to implement a routing table. Discuss about optimizing it.
Design an LRU cache with all the operations including getting the least recently used item to be O(1).
Given 2 lists find the intersection point of the 2 lists?
The characteristics of these lists are they at some point will share the same tail.
B->A->C->D->E->//
T->F->I->C->D->E->//
in this example ( C->D->E->// ) are the same list with same address space and nodes.
---------------------
B->A->C->D->E->//
T->F->I->
The lists can be of any length and not sorted.
1) give any method to solve this
2) if performance is a problem can we do this in linear time?
3) if space and performance is a problem, give a solution that will solve this in linear time without the auxiliary memory overhead.
4) code it
Given one huge linked list and one small linked list(both unsorted), how do you find intersection of these two lists(common elements).
delete a single link list which is a loop in it
What is the difference detween ISR & function call
How could a linked list and a hash table be combined to allow someone to run through the list from item to item while still maintaining the ability to access an individual element in O(1) time
what type of values cant be used in switch case can we use alphabets,floats,strings
do inplace merging of 2 arrays
Write a function to shuffle a deck of 52 cards. Explain how you would test that the deck was properly shuffled
Write a function to determine whether the binary representation of a specified 32-bit integer is a palindrome. For example, the 32-bit integer 0xFCA8153F is a palindrome, but 0xFCA88ACF is not. Show how you would test this function.
where is the memory map for the process stored and is it in hardware or in software
Two databases, each containing n elements (for a total of 2n elements, with no two elements being the same). Want to find the median (n-th smallest value). The only way you can access these values is through queries to the databases. For each query, you can only specify a parameter k and the chosen DB will return its k-th smallest value. Give an algorithm that finds the median using at most O(log n) queries.
What function(s) or hook(s) would you use in Drupal to define a url that maps to a function?
• hook_url
• hook_menu
• hook_form
• hook_uri
What function(s) or hook(s) would you use in Drupal to create a link?
• link()
• url()
• l()
• create_link()
What does the GD library do?
How can you get round the stateless nature of HTTP using PHP?
Which of the following characters anchors a regular expression pattern to the start of a string?
• ^ (caret)
• $ (dollar)
• % (percentage)
• ! (exclamation mark)
• * (asterisk)
What does the following code do? Explain what’s going on there.
$date='08/26/2003';
print ereg_replace(“([0-9]+)/([0-9]+)/([0-9]+)”,”\\2/\\1/\\3”,$date);
What function would you use to pull an associative array of results in mysql? An indexed array?
• mysql_query
• mysql_fetch_array
• mysql_fetch_row
• mysql_result
What function can you use to open a file for reading and writing?
1. fget();
2. file_open();
3. fopen();
4. open_file();
What function would you use to redirect the browser to a new page?
1. redir()
2. header()
3. location()
4. redirect()
Given the following code:
class myclass {
private $var = '';
var $var2 = 'test';
public function print_var() {
if (!empty($this->var)) {
print $this->var .'(Var1)';
}
else {
print $this->var2 .'(Var2)';
}
}
public function __set($string, $value) {
$this->$string = $value;
}
}
$myclass = new myclass();
$myclass->var = 'Hey there!';
$myclass->print_var();
What happens if $myclass->var is replaced with $myclass->var2?
• It prints ‘Hey There(Var2)’ to the screen.
• It prints ‘test’ to the screen because var is never correctly set.
• It throws an error because you haven’t set privacy settings for var2.
• It prints (Var1) to the screen because var is a blank string, not empty.
Given the following code:
class myclass {
private $var = '';
var $var2 = 'test';
public function print_var() {
if (!empty($this->var)) {
print $this->var .'(Var1)';
}
else {
print $this->var2 .'(Var2)';
}
}
public function __set($string, $value) {
$this->$string = $value;
}
}
$myclass = new myclass();
$myclass->var = 'Hey there!';
$myclass->print_var();
What happens when the code above is executed?
• It prints ‘Hey There(Var1)’ to the screen.
• It throws a fatal error because var is inaccessible in this context.
• It prints ‘test’ to the screen because var is never correctly set.
• It throws an error because you haven’t set privacy settings for var2.
Which of the following guarantees that the first letter of a string is capitalized and all other letters of a string are lower case?
• ucfirst($str);
• strtolower(ucfirst($str));
• strtoupper($str[0]);
• ucfirst(strtolower($str));
• strtoupper(strtolower($str)[0]);
A class is written so that it cannot be extended. Which of the following PHP 5 keywords achieves that goal?
• Static
• Abstract
• Private
• Terminal
• Final
If $a = TRUE, $b = 1. What does $a == $b equal? $a === $b?
• TRUE, FALSE
• TRUE, TRUE
• FALSE, FALSE
• FALSE, TRUE
What is better Inheritance or Composition and why ??
What is the difference between foo() & @foo()?
What functions can you use to add library code to the currently running script?
In PHP5, what code would the following print to the browser? Why?
$string = 'Hello';
function hello(&$string = '') {
$string .= ' World!';
print trim($string);
}
hello();
hello($string);
hello($string);
• World!Hello World!Hello Hello World!
• Hello World!Hello World! World!
• World!Hello World!Hello World! World!
• Hello World!Hello World!Hello World! World!
• Nothing. It would throw an error.
What would the following code print to the browser? Why?
$num = 10;
function multiply(){
$num = $num * 10; }
multiply();
echo $num;
Which of the following is true about asort?
• Sorts highest to lowest by value maintaining key association.
• Sorts lowest to highest by key maintaining key association.
• Sorts highest to lowest by key, re-indexing the array.
• Sorts lowest to highest by value, re-indexing the array.
Which of the following maintain index associations?
• ksort
• asort
• sort
A satellite moving at constant speed can orbit the moon one time in eight hours. After each complete cycle, the satellite instantly reverses direction a quarter of the way back around the moon before immediately continuing forward again for another complete cycle. Beginning in the forward direction above a particular spot of the moon, how many hours does it take the satellite to orbit that spot three times?
Note: Rotating to the spot and immediately reversing direction does not count. If you are continuing beyond the point, the time immediately over the point is considered the time when you orbit over the spot.
36 Hours
32 Hours
24 Hours
56 Hours
44 Hours
Three different springs bounce at different frequencies. Spring A bounces off the ground every 2 seconds; Spring B bounces every 5 seconds; and Spring C bounces every 9 seconds. The three springs leave the ground at the same time and continue bouncing until eventually the three springs, one by one, bounce during a three consecutive second interval. Upon the second and third such intervals, respectively, which spring makes the third bounce?
Note: Springs must bounce in 3 consecutive seconds (A,B,C/B,A,C/C,B.A/etc/etc), but more than 1 spring can bounce at the same time for it still to count. (A,B,C&A is acceptable. A&C, 0, B is not).
Springs A and C
Springs A and A
Springs C and A
Springs C and C
Springs B and A
One-fourth of X is one half of a number that, if quadrupled and added to X, would result in a number that is three times X. Which of the following numbers could not be X?
60
32
45
All of the following numbers could be X
40
Write a unix program to count the number of lines in a text file
What is pi?
What is polymorphism
What is the importance of the keyword static in java
Write a program to replace string 'us' with 'them' from the following String . Do not replace 'Us' as well as any string containing us
$_="Us? It usually rains when bus comes to us";
What is reflection
Explain what stack overflow and heap overflow are, and how they impact security.
Given two buffers; how would you deduce whether or not they are overlapping?
At the end of the discussion; he showed me a one line code for that.
Imagine a system where gas service to homes is controlled by a server of a service provider. How would you create a secure protocol for transfer of msgs. between this server and the apparatus at every home?
Assumption - The apparatus is secure and couldn't be hacked.
Given an integer, print the closest number to it that is a palindrome - eg, the number "1224" would return "1221".
Which of the following will not add john to the users array?
1. $users[] = 'john';
2. array_add($users,'john');
3. array_push($users,'john');
4. $users ||= 'john';
Five boxes, A through E, are stacked in alphabetical order with box A on top. The bottom three boxes are simultaneously removed and placed on top with their vertical order maintained. If this procedure were repeated two more times which box would end up in the middle of the stack?
Box E
Box D
Box C
Box A
Box B
what is the diff between static and dynamic power
# Given a string *Str of ASCII characters, write the pseudo code to remove the duplicate elements present in them. For example, if the given string is "Potato", then, the output has to be "Pota". Additional constraint is, the algorithm has to be in-place( no extra data structures allowed) . Extend your algorithm to remove duplicates in the string which consisted of UNICODE characters.
# Given that, there are 2 linked lists L1 and L2. The algorithm finds the intersection of the two linked lists. i.e' "L1 intersection L2 " ( similar to intersection of 2 sets ). Write all the possible test cases involved in the above given problem.
U have one String s1="WritingCode" and S2="Code Writing". write one code which will check all the contents of s1 is present in the String s2.use index of Operator and set a flag at class lavel, if the the index== -1; set flag, break;
don't use substring or contains(chSeeq)
write a method to calculate the acute angle between a clock: clock(int hours, int minutes)in java.My suggestion is to attemp these programmes 1st.public int clock(int hours, int minutes){// 360/12 = 30 360/60 = 6
int angle = ((hours*30 - minutes *6)<0 )? minutes *6 - hours*30 : hours*30 - minutes *6 ;
angle = (angle > 180)? 360-angle: angle;return minutes;}
U have one String s1="WritingCode" and S2="Code Writing". write one code which will check all the contents of s1 is present in the String s2.
use index of Operator and set a flag at class lavel, if the the index== -1; set flag, break;
don't use substring or contains(chSeeq)
write a method to calculate the acute angle between a clock: clock(int hours, int minutes)in java.
My suggestion is to attemp these programmes 1st.
public int clock(int hours, int minutes){
// 360/12 = 30 360/60 = 6
int angle = ((hours*30 - minutes *6)<0 )? minutes *6 - hours*30 : hours*30 - minutes *6 ;
angle = (angle > 180)? 360-angle: angle;
return minutes;
}
design hash table
reverse linked list
mth element from last in linked list
you have infinite integers arriving in a stream.
find duplicates in them.
explain what is done in compilation phase and what is done in linking phase and where does assembler comes into picture if at all ?
what will happen if process without any children executed thread_join
you have an eight bit multiply operator that takes two 8 bit numbers and returns a 16 bit value. Given two 16 bit values stored in 32 bit int variables, find the product using the
8 bit multiply operator.
is this valid syntax in 'C'
int a[10];
a = a + 1;
swap bits in position i and j for a number....in the most efficient way....
code to remove duplicate characters in a string.
3. printing a number in a matrix in snake like order
2. counting number of binary 1s in a number.
C coding
1.calculating power( M, N ) in log N time, power( 2, N ), finding if a number is power of
'2'
3. printing a number in a matrix in snake like order
2. counting number of binary 1s in a number.
C coding
1.calculating power( M, N ) in log N time, power( 2, N ), finding if a number is power of
'2'
WHY CONSTRUCTORS NEED NOT TO BE DECALRED AS VIRTUAL
can process which is sleeping at uninterruptible priority be interrupted by higher priority process
what r the advantages of blocking process compared to busy waiting and do blocking process consume cpu resources.
How will you test a module which ranks query completion suggestions in a search engine??
There is an sorted array containing some no. Now a no is chosen randomly and all the no on left are shifted downwards and all the no on right are shifted upwards now if have to find any no in the new array what will be the best algorithm?
What are some things to take care of when definining - a) Copy constructor b) Assignment operator?
There is class having a constructor taking a single int argument (there is no default constructor). Declare an array of 500 objects of that class.
There is a log file where each line contains fields separated by spaces. One of the fields is the IP address of the source node. We want to find the list of IP Addresses that have the most log entries. Lets say find the top 10 IP Addresses with most log entries. Give the pseudo code for this?
Implement multiplication of two integers using recursion. You cannot use loops or multiplication/division operators. How will you test it? Make it work for negative integers too.
a) We have Customer objects and we want to retrieve customers by birth date. Which data structure would you use? What is the time complexity?
b) Now what if we want to retrieve customers based on a given range of birth days?
constants defined through $define are placed in what type of memory and do they follow block scope will o/p of print be 1
void main()
{
funct();
printf("%d",x)
}
funct()
{
#define x 1
}
What is the best efficient algorithm to find intersection point of two lines.
You are given four points A, B , C , d.
Find the intersection point between AB and CD.
Optimize the algorithm as much as you can.
Given char* func1(char* target, char* substring,char* replacement)
write a c++ code to find the substring in the target and replace the whole substring with the replacement. (hint: replacement can be larger or smaller than the substring.)consider all possible test cases and check.
1. a Q about stack overflow and some design questions about distributed system protocols;
2. merge two sorted list;
3. rotate an array by K;
4. Given an XML string, check if it's valid or not;
5. binary tree: each node has an additional field node which is initialized to be NULL at first. Asked to, for each node, point its next pointer to the next node in level-by-level traversal order. NO QUEUE should be used HERE!
I think the recruiter matches me to the wrong team which focus on C# , but I know nothing about C#! So failed for sure:(
find LCA (lowest common ancestor) for non binary tree.
Write a program which makes the probablity of getting the even number when a dice is thrown in 72%( some number other than 50%).
write a singleton class and explain how u can create instance of this class using static func in this class. Explain which constructor is called when u create instance using this func ?
write c code for checking if given binary tree is balanced ?
Make a T Flip Flop using a D Flip Flop
What is the function of a D-flipflop, whose inverted outputs are connected to its input?
What advantages do synchronous counters have over asynchronous counters?
What types of flip-flops can be used to implement the memory elements of a counter?
Tell some of applications of buffer?
What is D-Word, Q-word?
If inverted output of D flip-flop is connected to its input how the flip-flop behaves?
Write a program to find the square root of a given number.
He wanted some kind of binary search.
One real mind-boggling question: Rewrite malloc and free so that they detect memory corruption. For example in a code,
ptr = malloc(5)
write(20); // you modify 20 bytes starting at address ptr
free(ptr);
Device a function that removes the occurences of blank spaces from a string. Constraints: run in linear time and the algorithm must be in-place. For example if,
string = Hi there wassup
output = Hitherewassup
Device a function that removes the occurrences of string2 from string1. For example if,
string1 = HelloWorld
string2 = llo
output = HeWorld
For the following piece of code:
func(int d)
{
int temp;
while(temp)
temp--;
}
How does the compiler behave differently if the variable temp is declared with the volatile 'qualifier' ?
This question was asked by the device driver's team: Can a variable be declared with both the 'const' and 'volatile' qualifiers ?
Describe a (n log2 n) time algorithm that, given a set S of n real numbers and another real number x, determines whether or not there exist
two elements in S whose sum is exactly x.
You are given have a datatype, say X in C.
The requirement is to get the size of the datatype, without declaring a variable or a pointer variable of that type,And, of course without using sizeof operator !
what are the advantages and disadvantages of little endian vs big endian and vice versa?
print the first n fibonnoci numbers using recursion
Third round:
you are given a M x N matrix with 0's and 1's
find the matrix with largest number of 1,
1. find the largest square matrix with 1's
2. Find the largest rectangular matrix with 1's
does sleeping process releases its resources ?
Telephoic:
Given a linked list, findout wether it is a palindrome or not,
I have given a solution with extra space, after that he asked as ..
No extra space is allowed,
expecting most efficient
telephonic:
write an efficient function to find the diametre of a tree,
diameter is the largest distance between two two nodes.
Find if there are any pairs of numbers in a list which can be added up to a target number.
How would you design an elevator control system in the highrise?
How do you find sequences of consequtive integers in a list that add to a particular number.
How to develop a sorted lexicographic tree.
How to find distance between two lines in a 3D plane
How to implement tries to create a tree, and find the words as per the prefixes.
Put eight chess queens on an 8×8 chessboard such that none of them is able to capture any other using the standard chess queen's moves
How to develop test case for iPhone
how to build a m way search tree.
Replace all 'A'/'a' with 'one in a sentence..
Do not use the inbuilt replace function.
Removed due to signed agreement for non-disclosure of proprietary information.
Keeep takin user input of numbers. Stop when user prints zero. Find the average of these numbers leaving out the 3 max numbers.
example: user inputs-> 2 3 4 5 6 7 8 9 10 40 50 60
then average should be: [2+ 3+ 4+ 5+ 6+ 7+ 8+ 9 + 10]/9
Removed due to signed agreement for non-disclosure of proprietary information.
which is the best sorting algorithm. I told quick sort then he wanted me to proove that its complexity is logn in best and avg case
Given a tree in which each node is an integer and an array with a set of integers, determine if all the elements of the array are present in the tree by visiting each node in the tree at most once.
#include<stdio.h>
int main()
{
int a;
char *x;
x=(char *) &a;
a=512;
x[0]=1;
x[1]=2;
printf("%d\n",a);
}
It gives 513. But I don't understand why?
Write the test cases for testing a pencil.
Write the test cases for testing the gmail first page application.
For a given integer number, reverse the digits of the number.
For a given string of size n, check whether it forms a palindrome or not by using the letter in the string.
Given a array of n integers we need to find the second largest number in it. And generalized to find nth largest number.
Write the test cases for it.
Given two linked lists which all the nodes in the linked list holds single digit of integer value, add the two linked lists and send the resultant list.
Write all the test cases to test the application given batch file which holds data format
ProductNumber, DiscoutNumber, Date on which the discount come into play.
Write all test cases for a function int fun(x,y,z) which performs operation like..
x*z+ (x+1)*z+……+(y)*z.
Given a puzzle that there are n statements such that each ith statement says that that many statements are false. Identify the number of true statements for a given N statements.
Given an application which is installed which is not coming up like gtalk. give the testcases for it.
Given program to write the Max product of the three numbers for a given array of size N.
Write all the test cases scenarios to test a save draft feature in the mobile phone.
Given an api [int sum(int ,int)] write all the test cases for it.
Write a program for a function which takes two lists(l1,l2) and return a node which merges the two list as follows.
l1:a ->b->c->d ->null
l2: 1->2->3->4->null
l3: a->1->b->2->c->3->d->4->null
Write a program which takes a integer number and adds all the digit in the number. It should return a single digit in the end.cc
Write code to print all combinations of a string
object oriented design of a general messaging system aka publish-subscribe
Given really large (beyond normal memory limits) with data in some sort of tokenized format,
write code to print top "n" frequently occuring data.
consider an integer array , for ex: [3,5,2,4,1,1,,6]
Permutation of array means re-arrangement of elements in different indexes.
Comparing 2 permutations would be similar to string sorting,i.e index 0, index 1 , index 2 etc.
Question , Given an integer K, right code to print array permutation at Kth position.
Asked to write code and dictate
given a file with heirarchial input like below.. create xml representation..
a.b.c=1
a.b.d=4
a.e=6
input can be assumed to be sorted and is heirarchial in nature.
output should look like
<a><b><c>1</c><d>4</d></b><e>6</e></a>
asked general algorithm and approach.
Design the classes and object for a file system.
Write code to reverse a string. Optimize it.
Write a method fill up an array of size n - and returns the array to the caller - with the following conditions
1. the numbers shud be between 0 to n-1
2. no repeated numbers
3. the method should have a deterministic time to fill the arrays
4. arrays returned from the method should have low-correlation factor
What is the use of static functions in C
Given 2 set of arrays of size N(sorted +ve integers ) find the median of the resultant array of size 2N.
(dont even think of sorting the two arrays in a third array , though u can sort them. Try something better than order NLogN )
Given two arrays of numbers, find if each of the two arrays have the same set of integers ? Suggest an algo which can run faster than NlogN without extra space?
Given two arrays of numbers, find if each of the two arrays have the same set of integers ? Suggest an algo which can run faster than NlogN without extra space?
Given 2 set of arrays of size N(sorted +ve integers ) find the median of the resultant array of size 2N.
Give an example of circular linkedlist in windows system
Write an program to add and subtract two numbers, the numbers can be of any length you can chose of language.
Convert a decimal number to its roman numeral representation. Now write a program to do the reverse.
You are a given a very large line delimited file
with a phone number on each line. How would you remove all duplicates? can you remove duplicates in less than O(n). if yes how?
How would you test an instant messaging app for a cell phone?
How would you test a vending machine?
How would you test Bing?
Write a function that generates random numbers between 1 and a billion.
Write a function that gets an integer and returns its string representation in Roman numbers.
Write test cases.
Write a function that returns all the prime numbers from 1 to a given number.
Write test cases.
Input: string s, char a, char b, int distance
Return true if both a and b exist and the distance between then <= the distance in the input.
Write test cases.
How would you test an elevator?
Input: a string. If the input matched the pattern: x="y", return y else return an error.
Write test cases.
Some hints: think about a state machine.
We also had a discussion on how to best return an error (error code, exception, error object)
Remove duplicates from a string. Write test cases.
Find an item in a sorted link list.
Write test cases.
Don't forget to ask if the list is sorted in an ascending or descending order.
Design anti-virus software.
What is the size of a VPTR? where is it stored?
Why do you use virtual functions? What is a VTABLE? How does it work?
What are inline functions? How would you reduce the chances of gcc making a function inline(means accepting the inline request from the programmer)
Generate a binary search tree from a continuous stream of numbers.
Will malloc work if RAM is 5MB , 1st two MBs are full and the 4th MB is full and it has to allocate 1.5 MB of data(basically there is fragmentation).
What's the difference between static and dynamic allocation. Can new be overloaded? Why would you overload new?
Explain the difference between structured and object oriented logic
Given an array in which one number occurs an odd number of times and all others an even number of times. Find that number.
How do you find the maximal sum sub-matrix in a given matrix? The input matrix may contain negative as well as positive numbers.
# Rank the following attributes in order of importance when designing new code. If you have time, please add a sentence to each explaining it's position:
* performance
* maintainability
* correctness
* ease of use
* ease of learning
How to completely delete a linked list with circle?
Implement N stacks using
constant sized array(space). Until the array
is completely filled, I should be able to push
elements to any one of the N stacks.(i.e.)Do
not reserve space for the stacks. And I should
also be able to pop elements from any stack.Given an array, find the longest subarray which the sum of the subarray less or equal then the given MaxSum
int[] FindMaxSumArray(int[] array, int maxsum)
for example, given array: {1, -2, 4, 5, -2, 6, 7}
maxsum=7
the result would be: {1,-2, -2, 6}
find the submatrix of a matrix with the maximum sum. Matrix consists of both +ve and -ve numbers
A binary tree with n nodes is given. Now find total number of distinct paths between any two given nodes.
protection bits, referenced bits are part of physical address space or virtual address space ?
What data structure would you use to store distances between all the planets in a galaxy. (So there could be like a billion planets)
Also steps in connecting a thin mobile client to connect to the server and get distances between one given planet and all the other planets in that galaxy.
You are given $100 and list of share market values for a period of 30days. You are allowed to make only one buy and one sell. Design an algorithm to maximize the profit.
how can be give default values to class variables without constructor
How to print the arguments recieved by main()?
how do u decide to use c or c++ and compare both language ?
someone walks into your room and dumps a huge bag of quarters all over the floor. they spread them out so no quarters are on top of any other quarters. a robot then comes into the room and is programmed such that if it sees a head, it flips it to tails. if it sees a tail, it throws it in the air. the robot moves around randomly forever. will there be a convergence in distribution of heads vs. tails?
Among a billion stars, find k closest stars
Design a web server logging system with 6 remote sites and a main site.
Given a binary tree, write code to find if is a symmetric tree.. Extrapolate it to n-ary trees.
Given two arrays of chars, find the longest common substring.
Write code to reverse a string.
Reverse a 32 bit integer
i challenge you to a game. we each get one penny and we flip them at the same time. (so on turn 1, we each flip our respective pennies - turn 2, we flip them again, and so on until someone wins). i am looking to get heads then tails. you are looking to get heads then heads. so if you flip heads on any flip and then heads on the next flip, you win. if i flip heads on any flip and then tails on the next flip, i win. (its not a speed race, we both flip at the same time, except i'm only concerned with what appears on my coin, and you are only concerned with whats on your coin). are the odds fair? (obviously not, otherwise this wouldn't be a question). who has the advantage and why?
why is it possible for base class pointer to point to derived class
is there difference between doing right shift on signed and unsigned no.s
whats the difference between o/p on little endian and big endian architecture and why
int x=1;
printf("%c",(char)x);
printf("%c",*(char*)&x);
for a binary tree find out if there exists a path between 2 given nodes
Implement the function
bool pairExist(int * arr, int sum)
where arr is an array.
The function returns true if there exists a pair in arr such that the sum of the pair is equal to the function parameter 'sum'.
You are given a bunch of emails in an inbox. You want to send all the sender addresses to some server. You can send them in batches (each batch containing a bunch of sender email addresses). The restriction is that no batch can contain duplicate email address. How would you write a program to send all the email addresses in batches such that it takes the minimum number of batches.
Analyze the complexity
what will be the o/p of this code
int i=0;
arr[]={0,1};
printf(%d,arr[++i]);
Find the K'th Maximum Element in a Binary Search Tree . Do it in O(log N).
Please dont do a in order tree traversal and return the K'th element from the end. I told that but interviewer did not wanted me to traverse the entire tree. Any suggestions ?
Given an Array. How would you search for any element if the last element repeated infinite times.
Given an Array. How would u search for an element?
Given an array of n numbers. Find all possible sum.
Two trees s and t are isomorphic if s can be transformed into t by swapping left and right children of some of the nodes of s. The values in the nodes are NOT not important in determining isomorphism, only the shape is important. Write a function IsIsomorphic that returns true if two trees are isomorphic. You must give the big-Oh complexity (in the average case) of your function with a justification.
Two binary search trees s and t are value equal if every value in s is in t and every value in t is in s. The shapes of the trees don't matter, the collection of values stored in s must be the same as the collection stored in t for trees to be value equal. Describe an O(N) algorithm for determining if two trees are value equal.
given a 3 number discrete random number generator {1,2,3} , how can you design a 5 number random generator ? What is the average number of trials necessary ?
on what type of memory volatile variables allocated stack/data/heap
How many constructor (including copy constructor) and destructors will be called for test1 and test2?
#include <iostream>
using namespace std;
class Base{
public:
Base(){cout << "Base()" << endl;}
Base(const Base&){cout << "Base(const Base&)" << endl;}
~Base(){cout << "~Base()" << endl;}
};
Base func(Base b){return b;}
void test(){
Base a;
func(a);
}
void test(){
Base a;
Base b = func(a);
}
int main(){
test1();
test2();
return 0;
}how to give default values to structure variables
Given a constant number of priorities implement a priority queue with O(1) enqueue and dequeue implementations
why combination of inorder and preorder traversal yields a unique tree while any other combination does not yield a unique tree like combination of post and inorder traversal
In an inbox, you have a lot of emails. You want to send all the sender addresses in the inbox to another server. You can send it in batches. But each batch cannot have duplicate addresses. Write a program to send all the addresses in batches such that you send minimum number of batches.
Analyze the complexity
Difference between final, finally and finalize in Java
Write a program to detect cycle in a link list and that take O(n) time
Write a program to find all the nodes in a binary tree that is in a particular level.
why class without private constructor can't be inherited and is there any way in which this class can be inherited
Explain in place merging of two sorted arrays?
there is one function which takes string as an argument and do some manipulation and return one unique integer corresponding to that string. Now user can pass either integer or character as an argument function should work fine even when user passes int as an argument like function can convert int into string and do the work write this functions prototype and how u will handle int case
implement dfs on binary tree without recursion
can we use conditional statements in switch case
say i<=10 && i>=0 can this be a particular case
what will be the o/p of print and why ?
void main
{
char *str=func();
printf("%c",*str);
}
char* func()
{
char *mystr='a';
return mystr;
}
what is the difference between these two lines
int x=1;
printf("%d",x);
printf("%c",*(char*)&x);
what will be o/p of each line explain in detail
using recursion print first n fabnnocci numbers. Remember we are not only finding nth fabinnocci number but we are also printing all the fabinnocci numbers
write c code for finding number of unique trees that can be made by n node binary tree
given an integer between 0-999,999 print an English phrase that describes the integer
ER diagram for a company which has people and professionals, investments in other companies
reverse singly linked list
Given two nodes P,Q on a tree, find the smallest subtree containing both of them. If p=q and also if p!=q4
Given 2 sorted array print their intersection.
Write down the C code to remove the substring from the main string. This should be done recursively.
e.g
main string = "hello xyydd"
sub string = "yd"
o/p = "hello x"
#1 recursion o/p = "hello xyd" //first "yd" removed but it formed new matching substring that has to be removed in next recursion
#2 o/p = "hello x"
Find the rectangle of maximal area under a histogram.
Mobile application with 3 screens.
1.Login page.(contains username and password)
2.Register page.(first name,lastname,username,password,retype password,mobile etc)
3.Main page(textbox to enter phone number,textbox to send message,and submit button to send the message).
Requirements : Maximum time to send message = 2minutes.
Maximum time to get response = 2minutes
Maximum numbers of users to support = 1000
And only 20% of test automation.
Come up with all the testcases that you test this applications?
What are the performace testing you will do?
What are the security testing you will do?
let there be a n x n matrix. two points say (a,b) and (c,d) are there in the matrix. find all the paths from point1 to point2 such that none of the path follows a diagonal path between the two points
how would you know if a map is corrupted?
do itoa in o(n)
There is a recursive function which takes 2d array as an argument. How to pass 2d array to this function
1) Type of stl containers
2) difference in composition, agregation,association.
3) Predicates
4) Deadlock and Starvation
5) Raised condition
6) Diff in Conversion ctr and explicit ctr
7) diff in has_map and map
8) explain hash_map and bucketing
9) virtaul inheritance, diamond problem
10) function adaptors
11) fucntors
12) function objects
13) in how many ways two classes A and B be related to each other.
14) diff between vector and dqueue
15) Repopulation of dqueue and its complexity.
16) types of iterators
17) how would you implement a map.
18) concept of immutability.
Given N points in a place with their (x,y) co-ordinates. Find two points with least distance between them.
There are given n men and n women.
Each woman ranks all men in order of her preference
(her first choice, her second choice, and so on).
Similarly, each man sorts all women according to
his preference. The goal is to arrange n
marriages in such a way that if a man m
prefers some woman w more than his wife, and w prefers m more then her husband a new marriage occurs between w and m. If w prefers her husband more, then she stays married to him. This problem always has a solution and your task is to find one.
Johnny was asked by his math teacher to compute nn (n to the power of n, where n is an integer), and has to read his answer out loud. This is a bit of a tiring task, since the result is probably an extremely large number, and would certainly keep Johnny occupied for a while if he were to do it honestly. But Johnny knows that the teacher will certainly get bored when listening to his answer, and will sleep through most of it! So, Johnny feels he will get away with reading only the first k digits of the result before the teacher falls asleep, and then the last k digits when the teacher wakes up.
Write a program to help Johnny to compute the digits he will need to read out.
The Chef has one long loaf of bread. Let us say, of length 1. He wants to cut it into as many little loaves as he can. But he wants to adhere to the following rule: At any moment, the length of the longest loaf which he possesses may not be larger than the length of shortest one, times some constant factor. Every time, he is only allowed to cut exactly one loaf into two shorter ones.
Input
One floating-point number, 1 k 1.999, meaning the stated constant factor.
Output
First, you should output one number n, the maximal achievable number of loaves for the given value of the constant factor. Then, you should output any proof that this number of loaves is in fact achievable: n-1 descriptions of cutting, using the following notation. At each step, you print two numbers: first, the index of the loaf that you want to cut into two parts; second, the length of the newly created loaf (cut off from the original one). It is assumed that the starting loaf has index 0. Each newly created loaf will be given the lowest possible free integer index (so, at the ith step this will be i). Each time, the size of size of the original loaf will be decreased by the size of the newly created loaf.
Example
Input:
1.5
Output:
4
0 0.4
0 0.3
1 0.2
Your program will take as an input 'n' coordinates of type {(X1,Y1,Z1), (X2,Y2,Z2), (X3,Y3,Z3),...(Xn,Yn,Zn)} and from these 'n' coordinates print a list of 's' coordinates (where 's' is another input parameter less than 'n') which are closest to the origin (0,0,0) and a list of 't' coordinates (where 't' is another input parameter less than 'n') points closest to each other. Your solution should use an optimal strategy and minimal time / space complexity
Each cell of an N x N grid is either a 0 or a 1. You are given two such N x N grids, the initial grid and the final grid. There is a button against each row and each column of the initial N x N grid. Pressing a row-button toggles the values of all the cells in that row, and pressing a column-button toggles the values of all the cells in that column. You are required to find the minimum number of button presses required to transform the grid from the initial configuration to the final configuration, and the buttons that must be pressed in order to make this transformation.
int * p= NULL;
p = (int*) malloc(0);
what will be the value of p?
How would you traverse a linked list with complexity O(n^0.5)?
Given a sorted array A, how will you find out elements in that array (a,b,c) such that the sum of the squares of a and b is the square of c? You need to do it in O(n^2)
Median of BST in O(logn)
Write a program htoi(char *) to convert a given hexadecimal value to decimal.
What happens in all the 7 layers of OSI model if I type www.google.com or any other link?What do these layers do?
Reverse a string. Do it in place.
Removed due to signed agreement for non-disclosure of proprietary information.
given an i/p file with 4 billion integers produce a integer that doesnt exist in the file given u have only 10 mb memory
Locate the node which is the m-th node from the end of a linked list. e.g. linked list has 100 nodes and m=5, it would be node 95.
Writing a C code to find the endianness of a computer.
Write a function to transpose a NxN matrix. Do it in-place. e.g. m={{1,2,3},{4,5,6},{7,8,9}} ==> m={1,4,7},{2,5,8}{3,6,9}}. Function prototype is like this "transpose(dimension, pointer to 2-d array)".
In how many ways cube can be painted using three different colours
why r callbacks static functions
can friend function in c++ class directly access the private and protected members of the class?
I told friend functions cant directly access they need object of a class as an arggument and thru that object only they can access private/protected variables any comments ?
someone walks into your room and dumps a huge bag of quarters all over the floor. they spread them out so no quarters are on top of any other quarters. a robot then comes into the room and is programmed such that if it sees a head, it flips it to tails. if it sees a tail, it throws it in the air. the robot moves around randomly forever. will there be a convergence in distribution of heads vs. tails?
You are at a party with a friend and 10 people are present including you and the friend. your friend makes you a wager that for every person you find that has the same birthday as you, you get $1; for every person he finds that does not have the same birthday as you, he gets $2. would you accept the wager?
a man has two cubes on his desk. every day he arranges both cubes so that the front faces show the current day of the month. what numbers are on the faces of the cubes to allow this?
you can go to a fast food restaurant to buy chicken nuggets in 6-pack, 9-pack or 20-packs. is there such a number N, such that for all numbers bigger than or equal to N, you can buy that number of chicken nuggets?
oil mogul aha:!
you are an oil mogul considering the purchase of drilling rights to an as yet unexplored tract of land.
the well's expected value to its current owners is uniformly distributed over [$1..$100]. (i.e., a 1% chance it's worth each value b/w $1..$100, inclusive).
bcause you have greater economies of scale than the current owners, the well will actually be worth 50% more to you than to them (but they don't know this).
the catch: although you must bid on the well before drilling starts (and hence, before the actual yield of the well is known), the current owner can wait until *after* the well's actual value is ascertained before accepting your bid or not.
what should you bid?
Given two classes:
class B
{
public:
B(args_1);
B(args_2);
// and many constructors with different arg lists
};
class D : public B
{
public:
D(args_1) : B(args_1) {}
D(args_2) : B(args_2) {}
// and many constructors with different signatures similarly implemented
// some additional stuff specific to D
};
Assume that the arg list for B's constructors are quite long and may be
revised pretty often in the future, in which case D's constructors have
to be recoded correspondingly. Duplicating the update by copy-and-paste
will certainly work here. Can you propose a better way so that the
update can be done in one place without copy-and-paste duplication?
Please write a function that accepts a floating number and returns its square-root. You may not use built-in square root function from your language. However, basic operators like addition, subtraction, multiplication are allowed. Please take into consideration the floating precision.
I have a log that consists of more than 100 million lines. Each line is just a data about user login, login time, etc. I want to sort them based on user login, and then if there is a tie based on login time, etc. However, I have limited memory, so don't think of storing all of them in an array. The memory can only hold n data where n is much smaller than 100 millions. You can access the disk though although it is much slower. How will you do it so that it is as efficient as possible?
Please write a function that accepts a floating number and returns its square-root. You may not use built-in square root function from your language. However, basic operators like addition, subtraction, multiplication are allowed. Please take into consideration the floating precision.
I have a log that consists of more than 100 million lines. Each line is just a data about user login, login time, etc. I want to sort them based on user login, and then if there is a tie based on login time, etc. However, I have limited memory, so don't think of storing all of them in an array. The memory can only hold n data where n is much smaller than 100 millions. You can access the disk though although it is much slower. How will you do it so that it is as efficient as possible?
How do you efficiently use B-Tree data structure to store 10 digit phone numbers
Explain Memory Fragmentation
what should a bridge cum router device do upon receiving a frame?
GDB. How to catch corruption of a structure member using GDB?
convert binary search tree to sorted doubly linked list.
List the critical process names that run on a windows operation system, on boot.
Write, efficient code for extracting unique elements from a sorted list of array. e.g. (1, 1, 3, 3, 3, 5, 5, 5, 9, 9, 9, 9) -> (1, 3, 5, 9).
Write a routine to draw a circle (x ** 2 + y ** 2 = r ** 2) without making use of any floating point computations
at all
Propose a tree based data structure
to identify a node with nth rank with maximum efficiency
Is the virtual memory really virtual or does the OS allocate some memory for and it and where???
Is the MMU hardware or a software and what about the TLB???
Given a very large arrray (size not known) and your algorithm will fetch every k^n element (I mean the sequences index values are k,k^2,k^3). Now, what is the order of your algorithm?
Without using an additional linked list arrange elements such that all even numnbers are placed after odd numbers
How many processes are created in this snippet?
main()
{
Fork();
Fork() && fork () || fork ();
Fork ();
}
I got the solution as 15. Need to draw to explain better.
Suppose you want to implement an ADT on a set of integers S with the following operations:
• insert (k ) - Places k into S
• extract min(S ) - Removes the smallest element from S
• extract max(S ) - Removes the largest element from S
• min(S ) - Returns (but does not remove) the smallest element from S
• max(S ) - Returns (but does not remove) the largest element from S
Explain how to do this so min and max take O(1) time while insert, extractmin, and extractmax
take O(log n) time.
convert Binary tree to binary search tree in place.
write a macro that can take variable arguments
write your own random number generator that takes as an argument number n and returns the random number between 0 and n any use of library random function is forbidden
How can you think of a way to implement a stack using BST
consider 1,2,3,4,5,6,..... infinite ...
intialize
jump=2.
then 2,4,6,8 .... gets removed.
remaining: 1,3,5,7,9,11 ...
jump=3.
then 5,11, ... gets removed.
reamining: 1,3,7,9,13,15 ..
we carry on for jump infinitely. here 1,3 are 'blessed' as they will not be removed.
now,given a number 'n', propose a algorithm to find out weather it is a blessed number or not.
Find the first occurrence of an integer in an array of sorted integers.
Find the transpose of a square matrix using recursion
Q> how to run functions before calling main.
1> complexities of the following loops:
a>
for (int i=0; i < n; i++)
for (int j=0; j<n ; j *=2 )
int k = i*j;
b> for (int i=0; i < n; i++)
for (int j=0; j<n ; j +=2 )
int k = i*j;
c> for (int i=0; i < n; i++)
for (int j=0; j<n ; j *=3 )
int k = i*j;
You have a sorted array then you randomly rotate the array several number of times. now you have find the smallest element in the array.
known facts: 1> you know earlier array was sorted
2> rotations
What is the difference between pointer and reference. Where do we use reference instead of pointer?
Consider a binary tree.Now print out the preorder and inorder traversal by one pass through every node.
class Base{
int a;
public:
int b;
Base(){a = 10; b = 11;}
virtual ~Base(){};
class Derived;
friend Derived;
};
class Derived: private Base{
public:
Derived(){cout<<b<<endl;}
void p(Base b){cout<<b.a<<endl;};
virtual ~Derived(){};
};
int main(){
Base b;
Derived d;
d.p(b);
return 0;
}Can this code be compiled and why?
Having an int array, which size is infinite (no way to find out), how do you do a binary search?
you have an array of n integers, how would you find the integer pairs which sum to m? complexity?
Implement a queue that is FIFO. Explain the classes and methods used.
I explained a queue program that has an array that contains elements. A function push to add elements and a function pop to remove elements. I mentioned that "pop" will check to see that the next position to popped has non-null value.
Interviewer asked "What if I want to add null values to my queue? what if I dont want size limitations enforced by an array?"
I understand that my solution is not optimal. I would appreciate your thoughts on an optimal solution.
Thanks to careercup and all its users who share their questions/thoughts.
Write thread safe getInstance function of Singleton class.
In an integer array, find maximum sum of a sub array (sub arrays length can be anything <= the array length)
Convert a BST to doubly linked list in ascending order with out using additional space.
Actually the leftChild and rightChild pointer should point to previous and next nodes in the list.
I have a stack which contains some integer data. I want to find out the min[or max] value from Stack in O(1) time. Any idea?
What should be the best way to invert a stack, without using any other EXTRA data structure, like a Stack2, or a temporary stack. Thus no stack1-stack2 or stack-queue-stack implementation in the answer. You just have access to push/pop feature of a standard stack.
Is there any algorithm using comparisons that check array duplication in O(n) time limit? i.e., Suppose we have a array of type double. Then I need a function like this
bool has_duplicate(double *arr, int len)that works in O(n) time in the worst case and checks whether it has to equal elements or not.
I want to calculate the factorial for numbers in the range 1 to 100. For small numbers, the function works but for bigger numbers for example 100! it returns incorrect result. Any ways to handle factorial of large numbers in C ?.
I have an array of values which is almost, but not quite sorted, with a few values displaced (say, 50 in 100000). How to sort it most efficiently?
How would you design a concurrency system for a linux shared memory given that-
-there are 1000s of readers
-because of the large num of readers and writers, they should not be allowed to obtain locks and block large number of threads.
Why should you not call a virtual method from within a derived class constructor?
void main()
{
int *p = 1;
p++;
printf("%d", p);
}
What will be the output, and why?
std::vector<int> items;
Referring to the sample code above, how do you remove all elements from the items
collections that are greater than 50?
a. items.erase(std::remove_if(items.begin(), items.end(), std::bind2nd(std::greater<int>(), 50)), items.end());
b. std::remove_if(items.begin(), items.end(), std::greater<int>(50));
c. items.erase(std::remove_if(items.begin(), items.end(), std::bindlst(std::less_equal<int>(), 50)), items.end());
d. items.remove_if(items.begin(), items.end(), std::bind2nd(std::greater<int>(), 50)));
e. items.remove_if_greater(items.begin(), items.end(), 50);
how to find Nth largest element in an array,complexity o(n)
How a new node can be inserted at the middkle of a link list in one single step? (Without traversing it)
How to efficiently find most frequent element in an array.?
Find the K'th Maximum Element in a Binary Search Tree . Do it in O(log N).
Please dont do a in order tree traversal and return the K'th element from the end. I told that but interviewer did not wanted me to traverse the entire tree. Any suggestions ?
if i write main like the following ways. Which one will compile and way?
1. char * main();
2. char * main(int, char);
3. char * main(char);
Search algorithm in ipod search. Please discuss the pseudo steps involved in it.
What all factors need to be considered while performing the search.
Thanks
Ankush
What if you are stranded with non performing team mates ?
Consider a prog. lang which has only single datatype called 'variable'. A variable x of type 'variable' can hold only +ve values(i.e 0<=x<=infinity).
We have only the following constructs defined in the language:
increment(x) -----> increments the value of x by 1.
setzero(x) ------> resets the value of x to 0.
loop(x) -------> loops x no of times.
Using the above constructs WAP to find x!/x.
Note: i) No other operator is allowed.
ii) u cant define ur own constructs.
iii) within the loop if the value of x changes then this does not change the value of x which is used to iterate.. for ex:
if we loop(x) with x=5
then there will be five iterations even if the value of x changes inside the loop...all the best !!
Difference between command and a program for ex ls is a program and for is a command
what is the most memory efficient sorting algorithm out of quick,bubble,insertion,merge,binary search
why is it necessary to keep visited flag for iterative post order traversal and not for inorder or pre order iterative traversal and is it possible to do post order traversal without keeping visited flag ?
write c++ code for implementing garbage collector
Given a year, print the calendar
You have a stack that is accessed by multiple threads simultaneously and you wish to
synchronize access. You do not want to use locking to implement synchronization. Implement
a thread-safe version of the stack
Convert date from mmddyy to words
How do you play war craft III
Code quicksort
write c or c++ code for finding longest substring in 2 strings using suffix tree ?
39. Given a n*m matrix having numbers such that each row and each column sorted. Now print the numbers in present in the matrix in sorted order
Given a M*N matrix A in which all the elements in a row and all the elements in a column are strictly increasing. Find a path from the smallest element (ie A[0][0]) to the largest element (ie A[M-1][N-1]) such that the sum of the elements in the path is maximum. Time Complexity O(m+n). Use efficient space.
how to compare 2 floating point no.s
find the nth prime number in fastest possible way
Write an printhex function which implements "%x" in printf without using printf.
Example :-
printhex(10) output is A .
Asked me what happens when a interrupt is received,told the standard answer but he asked me
what is contained inside an interrupt handler
Asked me to design a thread api
and asked me what happens inside for each call
and how the context switches from one thread to other
Asked me the process of system call ,what happens
exactly and how the mode toggles between user/kernel mode and vice versa
Reversing a linked list both iteratively and recursively
If you have a very large code base ,how do you
detect memory leaks in it with minimum changes
made to the actual code
Find the longest palindromic substring in a given string.
Write a function to check if two strings are anagrams. Write a fuction to find all possible anagrams of a given string. You are given a method isWord() to check if the string is a valid word in a dictionary. Assuming that preprocessing can be done what preprocessing will u do inorder to speed up the process of finding anagrams.
hree light bulbs and three switches. Identify each switch with its bulb.
There is a room with a door (closed) and three light bulbs. Outside the room there are three switches, connected to the bulbs. You may manipulate the switches as you wish, but once you open the door you can't change them. Identify each switch with its bulb.
How much should you charge to wash all the windows in Seattle?
Every man in a village of 100 married couples has cheated on his wife. Every wife in the village instantly knows when a man other than her husband has cheated, but does not know when her own husband has. The village has a law that does not allow for adultery. Any wife who can prove that her husband is unfaithful must kill him that very day. The women of the village would never disobey this law. One day, the queen of the village visits and announces that at least one husband has been unfaithful. What happens?
Imagine you have a closet full of shirts. It’s very hard to find a shirt. So what can you do to organize your shirts for easy retrieval?
If you look at a clock and the time is 3:15, what is the angle between the hour and the minute hands? (The answer to this is not zero!)
You've got someone working for you for seven days and a gold bar to pay them. The gold bar is segmented into seven connected pieces. You must give them a piece of gold at the end of every day. If you are only allowed to make two breaks in the gold bar, how do you pay your worker?
If you could remove any of the 50 states, which state would it be and why?
what is the difference b/w asif and faheem
How many binary tree can be formed if n number are given
a person dies, and arrives at the gate to heaven. there are three doors. one of them leads to heaven. another one leads to a 1-day stay at hell, and then back to the gate, and the other leads to a 2-day stay at hell, and then back to the gate. every time the person is back at the gate, the three doors are reshuffled. how long will it take the person to reach heaven?
this is a probability question - i.e. it is solvable and has nothing to do with religion, being sneaky, or how au dente the pasta might be ;-)
someone walks into your room and dumps a huge bag of quarters all over the floor. they spread them out so no quarters are on top of any other quarters. a robot then comes into the room and is programmed such that if it sees a head, it flips it to tails. if it sees a tail, it throws it in the air. the robot moves around randomly forever. will there be a convergence in distribution of heads vs. tails?
in a country in which people only want boys, every family continues to have children until they have a boy. if they have a girl, they have another child. if they have a boy, they stop. what is the proportion of boys to girls in the country?
A chinese emperor had to choose a new adviser amongst 3 sages, all of them equally wise. He placed a problem to them: "To choose one of you, you'll play a simple and fair game: In this sack there are 3 white balls and 2 black balls. Each of you will be blindfolded and will pick one ball and place it on your head. After that, the blindfolds will be removed and each one in turn will try to guess the colour of the ball upon his head, by observation of the other picked balls. However, beware. You may pass your turn in guessing, but if you state a colour and fail, you're disqualified. This way I'll learn which one is the most intelligent amongst you" The sages talked briefly to each other and promptly refused: "Dear lord, it's of no use, since the game is not fair. The last one of us to guess in the first round will know the answer." and the sages promptly demonstrated this to the emperor, who was so amazed by their wits that he appointed all 3 has his advisers. Could you demonstrated it ? NOTE: If the emperor had any wits at all he would have named them all advisers in the first place... maybe spending reduction ? :)
arrange the numbers 1 to 8 in the grid below such that adjacent numbers are not in adjacent boxes (horizontally, vertically, or diagonally).
___
| 1 |
=============
| 6 | 4 | 3 |
=============
| 2 | 7 | 5 |
=============
| 8 |
=====
the arrangement above, for example, is wrong because 3 & 4, 4 & 5, 6 & 7, and 7 & 8 are adjacent.
you have 12 coins. one of them is counterfeit. all the good coins weigh the same, while the counterfeit one weights either more or less than a good coin. your task is to find the counterfeit coin using a balance-scale in 3 weighs. moreover, you want to say whether the coin weighs more or less
than is should and, and this is the real kicker, your weighs must be non-adaptive. that is, your choice of what to put on the balance for your second weigh cannot depend on the outcome of the first weigh and your decision about what to weigh for round 3 cannot depend on what happened on either your first or second weigh. for example, you can't say something like "take coin #1 and coin #2 and weigh them. if they balance, then take coins 3,4,5 and weight them against 6,7,8...if 1 and 2 don't balance, then weigh #1 vs #12..." you
have to say something like:
round #1: do this
round #2: do this
round #3: do this
if the results are left tilt, balanced, and left tilt, respectively, then coin #11 is heavier than it should be.
How many wedding dresses were sold in italy last year ?
You're given N signed integers a[1..N].
You need to find N correct signs s[1..N] (that is, numbers s[i] = +/-1), such that
a[1]*s[1] + a[2]*s[2] + .. + a[N]*s[N] = 0.
Assume that the solution always exists.
Example: a = {5, 7, 3, -8, 1};
then the signs are: s = {1, 1, -1, 1, -1}
because: 5 + 7 - 3 - 8 - 1 = 0
(or symmetric solution: s = {-1, -1, 1, -1, 1})
Explain the difference between equals and "=="
What is hard copy and shallow copy?
Write down a piece of code to check if a given number belongs to the standard Fibonacci sequence? What is the time complexity of your code?
Find a two-line program to output the Nth Fibinacci number
Given a singly-linked list, output the contents in reverse order, without recursion or additional memory, and in efficient time.
Given two robots on an infinite line, they can move left or right. They cannot see each other. There is a marker between them that they can detect if they touch it. What algorithm will allow the bots to find each other (anywhere), if both bots are running the exact same algorithm?
You could have the bots go right then left in ever increasing distance. They will eventually find the marker. They could then stop and await the arrival of the other bot, or increase speed in that direction to catch up to it faster.
If the bots may only pick one direction and not change it, then they each pick, say, right, and move slowly until the marker is found, then increase speed to catch up to the other bot.
How do you explain the _BASIC_ difference between Java and C++ to your grandmother in 3 simple sentences?
First phone screening: What's the difference between a array and link list in details.
First phone screening: Difference between binary tree and binary search tree?
First phone screening: If you have implement a dictionary what possible data structures would you use?
First phone screening: Find if the sum of two elements in an array sum up to b (a number) ... with complexity of O(n)?
Design a efficient cache, supporting retrieval of maximum element in cache along with other normal cache operations.
Suggest data structures to be used,also tell the complexities for each of the operations.
Do iterative post and in order traversal without keeping visited flag
How do u implement quicksort and mergesort algorithms without using recursion!!!
please explain the logic n write the code
write an algorithm to reverse a binary tree.
explain DMA uptill finest detail
What is polymorphism?
What is an Abstract class? What is the difference between abstract class and interface?
Write a function that takes a string as an argument and returns the number of unique words in the string. Now write test cases to test this function.
When we declare a variable in C as volatile, what are the assembly level differences in the program, as in , when the code is converted by the compiler to an assembly level program, what are the differences???
A,B and C are one-dimensional arrays of size 100,50, and 200 respectively. Construct a program flowchart and corresponding pseudocode for an algorithm to store the first 100 numbers (1,2,3,4,5,..100) into array A, the first 50 positive odd numbers (1,3,5,7,..) into array B, and reciprocal of each position [C(5)=1/5] into array C. After all the arrays have been defined, output each array. Notice that no input is required. Be sure to plan a well-structured, modular program.
Given an array of m+n elements in the range 1 to n ie(m elements are repeated). Find the duplicate elements.
Time Complexity: O(m+n)
Space Complexity: O(m)
How will you merge two large files each containing a date field, a sequence number and one or more english word per line? The words are:
Case 1: sorted
Case 2: unsorted
The result should be sorted
Write a code to swap every two bits in a byte. (Using bit operators) eg: Input: 10 01 11 00 Output: 01 10 11 00
IN Hash is lookup always O(1). Explain why ?
Iterative preorder,post and inorder traaversal of a Binary tree?
finding common ancestor in a non binary tree ?
Among different sorting algorithms which one is best and why?
Design oxford english dictionary.
• Code should be in C or C++ and should be ‘production quality’. I.e. has to check for errors at runtime, and cannot overflow or underflow buffers or corrupt memory.
• Pls include a paragraph explaining how you would test this:
• Implement a routine that processes packets from the network over a reliable TCP connection:
HRESULT ProcessData(PBYTE pDataBuffer, IN ULONG cbBufferSize)// you need to implement this routine
Information:
typedef struct tag_HEADER
{
ULONG cbTotalPacketLen;
ULONG cbThisChunkLen;
#define FLAG_FIRST_CHUNK_IN_PACKET 1
#define FLAG_LAST_CHUNK_IN_PACKET 2
ULONG flags;
} CHUNK_HEADER;
The format the server sends will be a sequence of PACKETs.
Each packet is broken up into a sequence of one or more CHUNKs. Each Chunk starts with a CHUNK_HEADER.
The first CHUNK in a packet has ‘flags’ field set to FLAG_FIRST_CHUNK_IN_PACKET.
The last chunk that has ‘flags’ FLAG_LAST_CHUNK_IN_PACKET sets.
Chunks in the ‘middle’ of packet will have neither flag set.
A chunk can be any size up to 16384 bytes. A packet can be any size unbounded.
The ‘total’ length of the packet will be cbTotalPacketLen, each chunk in the packet will have this same length set in the chunk header.
The ‘length’ of the current chunk will be always ‘cbThisChunkLen’.
The ProcessData(...) routine will be called many times, with whatever data has arrived from the network. The network is reliable so data will arrive in sequence it was sent. However as this is a TCP stream, not a message there is no guarantee that the call to ProcessData will correspond to a complete chunk. I
That is important point, ProcessData may be called many times for even one CHUNK. And may be called with an arbitrary number of bytes each time ranging from just one byte.
Your goal: with ProcessData(…) is to implement a routine that reads the stream and the CHUNKs and from that reconstructs a _complete_ Packet (i.e. has data from all chunks in the packet). Once a packet is constructed you should pass it to a routine:
HRESULT ProcessPacket(PBYTE pPacketBytes, IN ULONG cbCompletePacketSize); //you do not need to implement this. Just call it EVERY time you have a completed packet.
In a computer which has a word size of 4 bytes, how do we read just a single byte?
Provide an example of synchronous and asynchronous signals
What signal is generated on divide by 0?
What do we mean by 64 bit architecture? What are the advantages and disadvantages of 64 bit architecture?
From which type of memory does shared segment come?
What happens when the following piece of code is executed?
Char *ptr;
While(1) ptr = malloc(1024*1024);
In execution is it possible for an old process to get control back?
In byte addressable memory, what is the smallest size of data accessible? Is it byte? what about bool?
There were 3 racers A, B and C. When A finished the race, B was 8 mts behind A and C was 16 mts behind A. When B finished the race, C was 10 mts behind B. Assuming that three of them ran at constant speed, find the length of the track.
Write a program that print numbers 1to 100 which are divided by 2 and 5.
Explain what is meant by synchronous and asynchronous bus.
Write a Java program that prints the size of a non-primitive Java object.
To check whether one linked list is reverse of the other without taking extra space o(n) space.
what s next in this series
sss,scc,c,sc,?????.
is it possible signals to be send in hardware and what is the example simillarly example of software and hardware interrupt ?
if we declare some auto/global variables inside a particular thread will they be visible to another thread too (remember threads share same memory space) ?
if thread allocate something dynamically will it be visible to other threads
in exec since pid of the new process has the same pid as the old process after exec. So what happens heap stack and other memory space of the process ?
pass array by value to a function
explain nested interrupts
difference between software development cycle in rtos and normal os
what is the best page replacement algorithm and why ?
What is the differnce between embedded systems and the system in which rtos is running?
WHY padding increases systems performance
advantages and disadvantages of Memory mapped I/O and Input mapped I/O
what is signal handler? In which space they are written user or kernel
In case of Mesi protocol where is the information stored whether block is in shared, invalid or modified state
explain what is saved in thread context switch and compare with process context switch
explain embedded systems properties of cellphone
What is the difference detween ISR & function call. In what language isr is coded c or assembly
To find the sixth largest number in the array without changing the array and without taking extra o(n) space and in o(n) time complexity.
how to reverse a linklist using recursion?
there s a 8 X 3 wooden piece. u r allowed to cut it oly once in any way yo want and arrange the pieces so as to make it 12 X 2 piece. how ll yo do it????
Write a function in C to check if a given string matches a
given pattern as a non-contiguous substring: that is, all the characters in the
pattern appear in the text string in the same order, but possibly not all in a
row.
1. Describe one of your projects
2. Write class for directed graph. How to detect a cycle?(DFS). Time complexity?
how will you read all english sentences from a text file containing normal english text e.g. a story or a simple document.
WRITE a script for searching a text john in entire directories (one directory can contain another directory) and replace it with TOM
There are N egg baskets and the number of eggs in each basket is a known quantity. Two players take turns to remove these eggs from the baskets. On each turn, a player must remove at least one egg, and may remove any number of eggs provided they all belong to the same basket. The player picking the last egg(s) wins the game. If you are allowed to decide who is going to start first, what mathematical function would you use to decide so that you end up on the winning side?
An apple is 40 cents, a banana is 60 cents , grapefruit is 80 cents. How much is a pear?
35 cents is paid by two coins one is not a dime. What are the two coins?
Given a string of 10 characters and a number, insert multiplies and
additions to make the characters equal the number
ie
1232537859, 995 -> 123*2+35*7+8*58
diff between malloc and calloc
assembly code to count 1st n numbers.
flip all odd bits of a number.
print all permutations of a string.
Given a search engine which uses a cache to store the search results. The size of the cache is 100 records and uses a LRU mechanism. Give test cases to test the features of the search engine, the caching mechanism etc
Design a deck of cards.
Write code for Shuffle() method.
Denition about ordered binary tree.
How to find the second largest node? Need specific code.
Deninition about hash map.
Space and time complexity.
Given a table: CustomerOrders:
Customer Orders
-------------------------------
Customer ID | Order ID | Order Date
1. Write a SQL to find all customers who has placed an order today.
2. Write a SQL to find all customers who has placed an order today AND yesterday.
you have a bag full of airplane tickets with various destinations. given two destinations find those tickets in the bag and give the cheapest routing in the least time possible
N people in a party. Find a celebrity among them. Celebrity knows nobody else, while everybody else knows him/her. You are required to do this by asking a single question to see if A knows B. The answer is yes or no. What is the minimum number of questions to be ask? What if there doesn't exist such a celebrity?
Given a sorted linked list, delete all duplicate numbers, leave only distinct numbers from original list. e.g., given 1->2->3->3->4->4->5, return 1->2->5. Given 1->1->1->2->3, return 2->3.
You are given a two dimensional array (say 5*5) in which all the rows as well as the columns are sorted. Describe an efficient algorithm to discover if an element is present or not.
Assume that you have a CPU with 4 (r1, r2, r3, r4) registers, which supports the following operations
zero(r) -- resets register value to zero
inc(r) - increments register value by one
loop(r) { /* loop body */ } repeats everything in the loop body x times where x is the value in the register r. The number of iterations does not change if x changes inside the loop body.
All the registers are integer numbers, not less than zero, and less than infinity. No operations, except from described above. One can not create additional registers or variables.
In this language, implement a function "r1 = r4 - 1" (assuming that r4 > 0)
How would you convert a binary tree into a binary search tree?.. write a efficient way of doing that?
Explain the boot sequence ?
Difference between Interrupt and a signal when to use each ?
Write a function that removes extra spaces from a string and leaves only one correct space. I got it right the first time so they changed and twisted it a lot.
Tell me about yourself. What are your strengths and weaknesses?
Write a function to print out misspelled words from a string containing many words.
Where are static variables stored?
Write a function to check if a stack grows up or down
Explain how virtual functions are implemented.
My final round was with a senior developer/manager. Very arrogant and intimidating lady. Didnt even shake hands or introduce herself. In one problem, she kept on pressing for a better solution all the while insulting some stuff on my resume, she was clearly testing my patience and see if I would give up. Wasnt happy with my answer and left in a huff..
I personally didnt like the work environment..people were sitting in straight rows without even cubicles and working on their terminals..dont know how they concentrate!
I got a feeling that they were looking for people who would take whatever shit they do to them and just do their job.
I did an onsite interview. Very swanky headoffices..comparable only to google. And free food! In one interview, I had two developers simultaneously. Not the brightest you meet...they were getting confused themselves. At some point, they showed me everything about the bloomberg terminal. I slipped my tongue a few times and openly criticized their crappy UI. They weren't happy with that.
Print a linked list recursively in a reverse manner without changing the actual list
if there r 2 processes with the same deadline in RTOS and we can run only 1 processes and both the processes are exactly same in everything like start time priority and all how will scheduler decide which process to run
after context switch processes which has interrupted other process starts running but how does os know which process to run after running current process. Simillarly in case of interrupt how does interrupt handler know where it should go back ?
what do you mean by address space of a process what essentially it is ?
What is the difference between process and thread context switch what all needs to be saved for process and thread context switch like do we need to save heap, basically she wanted me to list everything when i said registers she asked me to tell the name of the registers then she asked if process variables needs to be saved and so on ?
Write a c program to search for an element in a binary tree[not BST] and if found return its level. root is labelled level 0 and children are one level incremented than its parent.
if not found return -1
Given an array of N elements , one element is repeated N/2 times. Find the element if such an element exists.
Given a binary tree with the following node structure
struct node
{
//data
//pointer to left subtree
//pointer to right subtree
//pointer to sibling
};
The sibling pointers are NULL for all the nodes.Make the sibling pointers point to their respective nodes in O(n)time complexity
How do you shift a String given a String
For instance the following string abcdef and given an index 3, how would you make this in to defabc. So basically the index at a given point must be moved to the front and the rest of the string shifted to the right.
Another example:
Given an index 2 the result is cdefab
You have 32 bit Integer how to count number of one's in the Integer.
You need read a lot of records, you don't know how many records here
before you complete it. After you read all those records, you need select
one record randomly.In another words, every record has same chance to be
selected. The memory is limited, that means you cannot store all those
records at one time.
You have more than 3 million entries of phone numbers. You have to create a phone book just like the one we have on the new phones these days. You type the name, and the numbers that match the letters you typed shows up on your phone.
For e.g: When you type 'K' all numbers under K appear,then you say "i"...all numbers under "Ki" appear..so on and so forth.
How will you design/architecture this type of search? Discuss data structures you would use whats the worst case for your design?
You are participating in a game show in which a prize is hidden behind one of the 3 doors. you ll win the prize if u select the correct door. After u have selected a door the host opens a door which doesnt have the prize. he asks u whether u ll go for a switch?? What are ur chances of winning if u go for a switch?? what are the chances if u dont go??
Given 2 nos a,b such that 0<a<b as input provide an algo using fair coin flips, produces an output heads with probability a/b and tails with probability (b-a)/b.
Meeting Place Problem
In a company, cubical position of each employee is identified by its coordinate (i,j,k).
There are total N cubical and there are n employees in the company. (N-n cubical places are empty).
It take 1 unit of work to move in +X/-X direction , 2 unit of work to move in +Y/-Y direction and 3 unit of work to move in +Z/-Z direction.
Find an efficient algorithm to find meeting place in company so that total work done during movement by all employees should be minimum.(Meeting place could be empty cubical also)
Given a tree with N nodes and a N*N matrix. you have to fill in the matrix such that a[i][j]=1 if i is an ancestor of j else a[i][j]=0.
write an algo to Check whether a graph is a straight line.You are given an adjacency matrix representation of the graph which is a N*N matrix
You want to find the maximum integer in an array of integers. What would you use? Bubble Sort or Merge Sort? Would your answer change if size of array >1000.
Given an array of 100 numbers. When given any input, say 30, get the 2 nos. whose product will give the input.
Ex: for 30, the result should be,
2 15
1 30
3 10
5 6
Given a file with the following rows:
Student_name Subject Mark
Get the student from each subject who secured the highest mark
Write a script/code in any language to implement Binary search algorithm
What is Dynamic Hashing and write code to implement it.
Given a function randfive() that generates a number between 1 to 5, with uniform probability. Use this to write a function randseven() which generates a number with uniform probability between 1 to 7.
Given an int array and an int value. Find all pairs in array that add up to value.
What is the difference between using Assignment operator and Copy Constructor?
Given the below table:
LEDGER
ID VARCHAR(11) PRI
Month VARCHAR(2)
Year VARCHAR(4)
Amount REALCompose the query that will output the report in the following format:
Year 1980 1981 1982 ...................2009
Jan $$ $$
Feb
Mar
..
.
.
.
Oct
Nov
DecWhere $ if the total Amount for a given Month
Given the Function F(N) = F(N-1) + F(N-2), write an efficient implementation. What is the run time?
A computer has three registers, A, B and R. It has only three instructions:
A->R : Load R with A
B->R : Load R with B
A-R->A : Subtract R from A and store the result in A
Using these instructions how can you do the follwoing?
B->A : Load A with B
Write the strstr function, using of any system string fucntions such as strlen was prevented
Given an 8 bits, give the range of integers it can cover.
Given a large list of size n(value of n is order of billions) containing x,y,z co-ordinates of stars in space, and a small array of size m(order of 100-150) with earth as the origin, compute efficiently m-closest stars to earth.
Given an array of size n, you have n-1 integers in the array, and one of the n elements is a duplicate, find an efficient method of finding the duplicate.
How will u find the highest and second highest salary in each group using a single SQL query ?
Sort a linked list using bubble sort.
Given a sample string, say
String s = "This is a test string "
The idea is to remove or squueze all the extra spaces to a single space. Condition: The process should permanently change the string and not simply print the string character by character by ignoring extra spaces.
Given a sorted array and a value, determine the first pair of numbers from that array which sums up to the given value.
What is the difference between constant and read only?
What is the difference between string and stringbuilder? When would you use each?
When is using an interface necessary?
what's the difference between abstract class and interface?
Given an arrayList, how to reshuffule it?
Write a function to return the Fibonacii value based on the position(N), use both recursive and non recursive function
Has anyone tried this? http://www.facebook.com/careers/puzzles.php?puzzle_id=11
The brute force way is n! so definitely won't scale. I tried a little bit of pruning (where I keep track of expected time and as soon as I see that it's more than then current minimum expected time, I bail out). But other than that, can't think of any..
So here is I have uptill now:
for all permutations of possible paths:
find expected time for that shortest path
if (there is a path) and (expected time < min expected time)
minexpectedtime = expectedtime.
Can someone give me hints on pruning? I think I need a better way than going through all the permutations but am unable to think? Any help on algorithms/pruning/datastructure would be appreciated..
He showed me a puzzle with some domino like rectangular blocks joined together ( he had brought the actual blocks ) and a pattern on a card that has to be formed using the given blocks. There could be any number of lines in the pattern, and building block was composed of exactly 3 rectangles.
Assume 2 hyphens(--) as 1 (domino) block
So building blocks are something like this
---- --
-- --
--So each building block has 3 blocks in it..
Now using such given building blocks we have to form a pattern like this..
--
------
----If you have a vertical bar on which pizzas with a hole in the center are placed randomly irrespective of size. How would you most efficiently sort the pizzas so that the largest pizza is at the bottom?
If you are given a function that can generate uniformly distributed random numbers between 0 and 1, rand(). How to write a function to generate number x (between 0 and 2), with probability of 0.5x.
To be more concrete, the probability of generating 1 is 0.5, the probability of generating 0 is close to 0, and the prob of generating 2 is close to 1.
Replace a word "Old" with word "new" in all the files of the directory. Solution can be a linux script also.
In a particular directory, list the 15 recently modified files. ls -ltr | tail -15.
Find the nth Hamming sequence number?
http://perl.plover.com/Stream/stream.html#streams
Designed the parking lot. Asked a number of questions. Design thoughts on Aggregation, Composition, etc. Designed Classes. Had a lot of disussion on the flow. How to validate or invalidate Slot, ParkingLot and Vehicles. Wanted to make Park() method a O(1) instead of O(N). I suggested that we use a Stack to store the empty slots. O(1) was for UnPark(). I was not completely satisfied with the design - we were passing the variables in/out of the methods... The interviewer was happy anyways.
4. Then he wanted a bytewise reversal of a int. Wrote a function with bitwise or, etc. No feedback. Went overtime. And definitely wrong.
Then he wanted to implement Pow(A,N). Blunder with returning N instead of A. Before that he asked me to have a look at the func... Then he wanted the order. And the number of multiplications happening. And why call it logN. what does it mean...
Finding common integers from sets of two integer arrays. Used sorting & traversing O(M+N+NLogN+MLogM). Made it a order N by using hash.
1. Wanted to find LCA for two nodes in a BST - Confusion on BST vs ST (recovered) - On recursion vs iteration. When do you use what and why? Readability - tail recursion. I gave example of Fibonacci - Screwed me on that. Unlimited Heap space vs limited stack space. O(N^3) vs O(N).
Then he wanted to find the shortest path to convert one string to another using the minimum edits with each transformation string being a valid dictionary word (for->fork->ford->word->sword). Started on recursion. Suggested go with Graph (he was happy with that). In case of two paths leading to the same word replace with the shortest - eliminate the shortest. He wanted to know how we can terminate. Traversal: Breadthwise vs depthwise. Suggested we go breadth wise as that would be the shortest path as yet.
FirstUnique() character in a ascii string. Thought about tree, then something else. Then bling!!! Decided to use an Array of 128 chars. O(N). Coded it. Errors in while(str) instead of while(*str). Array declared as char freq[128] instead of int freq[128]. Finally anyways, came out well.
2. Question about how to design a feature in a Amazon page - Mail me when this item is back in inventory. Said cant use triggers. Discussed structures, suggested we do polling. Then polling the main item table. Instead said we could that when an item is added but that would also have unnecessary calls. Told that the answer was right but I am also looking at another approach. More about how to do efficient triggers/trackers... He said the answers are not wrong but he was looking at something like Message passing. Told him I had no frigging idea about that.
Say you have to design a Online role playing game. People can buy demons and weapns online. There are N demons and M weapons. Each weapon of class W inflicts some damage X on a Demon of class D (ie. decrease health of Demon by X). The question was to design a OOP system to accomodate this - make the program data-driven if possible - i.e to add a new demon/weapon, the user has to make as minimum number of compilations as possible. Used a Singleton for storing the Damage of Demon-Weapon combo. Coded in C++. About loading, said we use DB. He suggested config files - I protested that cannot be done because the file can be tampered - no single source of truth.
1.How to do floodfill algo without using recursion. Started saying we need to find the initial position when the interviewer clarified that a seed is given. Said use Queue with the seed given. The basic floodfill algo is about replacing all similar and connected gray values to be selected and replaced with another gray value. Two pixels are said to be connected if one lies to the north-south-east-west pixel of the another.
2. Design problem of train reservation system. No questions asked. Nothing about SRS. He stopped me saying that when such a huge requirement is given how do you go about designing the system. I suggested SRS, functional specs. He finally said he was looking for 'use-case'. ER design... didn't know the conventions (bad bad me). He wanted to know more about the MVC architecture etc. Said about Reservation, Seats. reservation Model object that has seats as child (Rails convention). How the pages, controller and models work.
Amazon has many visitors to its site. And it tracks what pages the customers visited, etc and other stuff. Lets say you store the data of customer id and the page id as a record in a log-file. Now assuming that you have created one log file for each day with that above data-format. Give me the way to find all the customers who made a visit on day1 and day2 and visited atleast two different pages. Say a customer visited two different pages on day1 and then comes back on day2 and visited some other page on day2 he should be listed.
Lets say the logfile1 has contents like:
c1 p1
c2 p2
c1 p3
c3 p4
c5 p6
And logfile2 has contents:
c10 c7
c4 p4
c3 p4
c5 p1
c1 p2
c2 p1
Then the customers you print out are c1, c2, c5.
Given a time what is the difference between the hour hand and minute hand.
You are given a big log file with integers (integers might be repeated, size can be in gig's). I want you to print K largest numbers.
My answer was:
Break the file into small buckets of integers and from each bucket k large numbers and finally find k large numbers from those individual k large number lists.
He asked me how do u find k large numbers in the individual buckets?
I said i will have to take an array to hold the k large numbers. The first number in the array is my largest number and if i find any other number larger than this then the latest is my largest and the earlier is my second largest number and so on....
How do you implement a queue with stack data structure?
Write a program (psuedocode is fine) to implement file diff utility
Why do you need the const in a copy constructor? For example, if you have Foo (const Foo &), why do you need the const?
Given the following MySQL table schema, write a query to return the employee with the 7th highest salary.
CREATE TABLE `employee_salary` (
`id` int(11) NOT NULL auto_increment,
`name` varchar(255) NOT NULL,
`salary` decimal(10,2) NOT NULL,
PRIMARY KEY (`id`),
KEY `IDX_salary` (`salary`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1
My Answer:
SELECT name, salary FROM (
SELECT name, salary FROM Employees
ORDER BY salary, desc
) WHERE ROWNUM >=3 and ROWNUM <=7something like that....
here is the discription
http://coldfusion.sys-con.com/node/43794
Write a class to extract basic data from an Amazon Product Detail web page when passed a URL The following information must be extracted into an array: ISBN10, ISBN13, Weight, Dimensions, and Current Price. This code must be written in PHP. An example URL is:
http://www.amazon.com/Biology-MasteringBiology-8th-Neil-Campbell/dp/0321543254/ref=pd_bbs_sr_1?ie=UTF8&s=books&qid=1233281929&sr=8-1
My Answer: it's really easy. Check for the values into actual page and then just truncate string accordingly
Write a basic web application, following the Model-View-Controller/Modular design pattern. The following URLs should be functional:
• http://www.server.com/index.php?page=showTime - Displays the current system time.
• http://www.server.com/index.php?page=showDate - Displays the current system date.
• http://www.server.com/index.php?page=showVersion - Displays the current PHP / Java version.
Each page should be represented by an individual class. Any of the following languages can be used: PHP
Utilizing two common Object-Oriented design patterns, write a set of classes, which can be used to log a given message. The message should be logged to either a MySQL database or a file, depending on a configuration setting. There should be only one connection opened to the database (or the log file should only be opened once) throughout the use of the application. ). Any of the following languages can be used: PHP
My Answer:
create a buffer to generate a log and then copy entire buffer to your designated file
but downsize of this method is .... you will loose all data if system fail to commite or fail to log...//power shutdown
Given an array of integers,Print the integers whose appareance are in odd times.
Need not worry abt order while printing the output.
Need Algotithm in o(n) time complexity.
Need efficient space complexity.
Write your own printf() function in C
Write a C program to reverse WORDS in a string
I am a good boy
would become
boy good a am I
u r not allowed to use any extra memory ur program should be space efficient
How will you test a mouse ?
How will you test a keyboard ?
How will you test a notepad ?
how would i deal with an irate distributor
how would i be an asset to there company
what would i do if there was a complaint with a buisness and one of my employees
I attended the amazon first round phone interview about 2 days back.It went well.But they didnt get back to me yet.Whether I should assume the feedback as negative or whether they take this much time to give the feed back even for first round?Could any please let me know?
User Bin Crash
You are on a cargo plane full of commercial goods when the pilot announces that the plane is short on fuel. Unless cargo is ejected from the plane, you will run out of fuel and crash. The pilot provides you with the number of pounds of weight that must be ejected from the plane. Fortunately, the manifest of the plane is both completely accurate, digitized, and you are a programmer of some repute. Unfortunately, your boss is going to be extremely unhappy, and wants you to exactly minimize the losses to the absolute minimum possible without crashing the plane. The manifest does not contain the exact quantities of every type of good, because you have so many on board. You may assume that you will not run out of any good in the course of saving the plane. You also realize this kind of program could be handy to others who find themselves in similar situations.
Write a program that takes a single argument on the command line. This argument must be a file name, which contains the input data. The program should output to standard out the minimum losses your boss will incur from your ejection of goods (see below). Your program will be tested against several manifests of several crashing planes; each with different data. Additionally, your program must be fast, and give the correct answer.
Input specifications
The input file will start with an integer number indicating the minimum number of pounds of weight that must be ejected from the plane to prevent a crash, followed by a new line. Each additional line in the file represents a commercial SKU (stock keeping unit) along with its cost (in dollars) and weight (in pounds). The format of these lines is:
<SKU label> <weight in pounds> <cost in dollars>
SKUs are represented as a combination of letters (upper and lower case) and numbers. Both costs and weights are integers. Each piece of data in a line is separated by white space. Lines are separated by a single new line character. You are guaranteed your program will run against well formed input files.
Example input file:
1250
LJS93K 1300 10500
J38ZZ9 700 4750
HJ394L 200 3250
O1IE82 75 10250
Output specifications
Your boss is not interested in exactly what you ejected to save the plane, he/she is currently only interested in how much it will cost the company. Your program must find the set of goods that will prevent the plane from crashing, and minimize company losses. It should print out the total value of goods lost as a plain integer, followed by a newline. Do not insert commas or dollar signs.
Example output (newline after integer):
9500
find the longest path in a tree
What is the next line in the following sequence:
1
11
21
Answer: it's 1211 and the next is 111221
Out of 10 coins, one weighs less then the others. You have a scale.
(A)How can you determine which one weighs less in 3 weighs?
(B)Now how would you do it if you didn't know if the odd coin weighs less or more?
There are n gas stations positioned along a circular road. Each has a limited supply of gas. You can only drive clockwise around the road. You start with zero gas. Knowing how much gas you need to get from each gas station to the next and how much gas you can get at each station, design an algorithm to find the gas station you need to start at to get all the way around the circle.
Implement a function to return a ratio from a double (ie 0.25 -> 1/4). The function will also take a tolerance so if toleran ce is .01 then FindRatio(.24, .01) -> 1/4
int FindRatio(double val, double tolerance, int& numerator, int& denominator)
Open a file as securely as possible (assume the user is hostile -- list all the nasty things that could happen and checks you would have to do to)
Difference between heap and stack? Write a function to figure out if stack grows up or down.
You have 2 supposedly unbreakable light bulbs and a 100-floor building. Using fewest possible drops, determine how much of an impact this type of light bulb can withstand. (i.e. it can withstand a drop from 17th floor, but breaks from the 18th).
Note that the ever-popular binary search will give you a worst case of 50 drops. You should be able to do it with under 20.
Suppose there is a stream of numbers 1 to 9. It may contain duplecates.
which data structure will u use.?
Which data structure will u use other than provided by STL?
I got phone interviewed with Bloomberg.
1)diff bet class and structure
2)syntax of copy constructor
3)why we need copy constructor?
4)why we need overloaded = operator?
5)signature of overloaded = operator for a class?
e.g. Myclass & operator =(const Myclass &)
6)why & used in return type of = operator ?
7)suppose :
class Myclass{
public:
Myclass(int a){m=a;};
private :
int m;
};a)how will u create an array of objects of Myclass on stack?
b)how will u crete an array of objects on heap?
8)what precautions should be taken to write a class's destructure?
9)what will u do to prevent others from creating more than one instances of ur class?
10)how will u make singleton thread safe?
10.1) what problem may occure with singleton at run time?
11)what is diff between "operator new" and "new" ?
12)what happens if new fails to allocate memory?
1. Suppose a dll allocates memory using malloc or new and user of dll releases that memory.Is this a good practice.If not then why?
2.An application runs fine with a debug version of a dll but crashes with a release version of same dll.
What can be the possible causes of this.
You retrive username and password from User.How would you protect it?Discuss different algorithms to protect the password along with there Pros and Cons.
1.Difference between GetMessage and PeekMessage?How are where would you prefer to use onre over the other.
2.Address of a function is passed as a parameter to CreateThread().What would happen?
3.How can you see all the thread running in an application in Visual Studio?
4.Interthread and Intrathread communication using sendmessage and reply message.
5.Discuss ThreadInfo structure.
6.Say there are multiple thread running in an application.How do you stop one thread and execute other and come back to original thread?
1. Difference between GetMessage and PeekMessage?How are where would you prefer to use onre over the other.
2.Can you use GetMessage to retrive message of thread running in different process?If yes then how?
Given two Arrays, there is intersection of elements in these two arrays. So now find all the elements which are common in both these arrays.
Suppose there is an element '#' repeated 2 times in both the arrays, then in the output we need to show two '#'s
write a function to enable a bit in a monochrome monitor given a point (x,y).
implement a counting semaphore in Java.
what is the difference between a Skip list and a hash table ?
Write a function which performs some task e.g. of adding 2 no. and return sum to the main function. now there is nothing wrong with the function syntax wise but the program crashes after the execution of return statement.
Expalin : Cross site forgery prevention - Cross site requests - cross site scripting
When / how / where do you use them.
How do you design cache server for a simple web application.
How do you make sure of the data consistancy.
How do update your data/cache.
Explain Hashing . Max time / Min time taken to search in a Hash table.
How do you use hashing for web based applications.
How do you find out intersection between two arrays - when they are sorted / when they are not sorted.
There was discussion on complexity of various algorithms.
Explain MVC Architecture. Can you explain how u used MVC architecture in your current project at financial institution.
You are given a plotter which can plot points provided to it in the form of 'x' and 'y' coordinates. The plotter hand can move horizontally or vertically only. Your program will be given a list of 'n' coordinates in the form of {(x1,y1), (x2,y2} ... (xn,yn)}. Your program must print a sorted list of all 'n' points that would represent the least cumulative distance for the plotter hand to plot all 'n' points in that sorted order. If you are feeling adventurous - modify the program to provide the same output if the plotter can also move diagonally
Oil excavation is a common phenomenon in the sea. At every excavation site a rig is setup to extract the oil. The only mode to reach a rig is by a boat. Men who would like to reach a rig use special purpose boats which can run on crude fuel available at the rigs and the shore. These boats can run a mile for every unit of fuel they consume. Each man on the boat consumes a unit of food for every mile he travels. Boats have a limited load capacity. The net weight, including the weight of fuel, food and the men, on boat should never exceed its load capacity. The weight of one unit of fuel is same as the weight of one unit of food. However, as the rigs are far from the shore in the sea it is usually a very long sail. The capacity of the boat available for fuel may not be sufficient to reach the destination rig directly. In such cases, the men may goto a near by rig to load required fuel. The men can also store food at the rigs as well as at the shore for later consumption. They must buy all the food they require to reach the destination rig at the shore only. And all the men who started should be together throughout the sail.
You should now write a program which can help these men decide the minimum amount of food they require to reach the destination rig. The positions of rigs and the boat's starting point are indicated as co-ordinates of a two dimensional plane with x and y axises of 1 mile units. Food at shore is available only in whole units.
Assume that the food and fuel are consumed continuously, that is if you travel a partial mile the number of units of food and fuel consumed is equal to portion of mile traveled.
Input
The first line of input has a list of integers terminated by -1. The first integer is the capacity of the boat. The integers following it up to -1 are the weights of men who need to reach the destination rig.
Lines following will have two integers separated by a space, each line indicating the x and y coordinates of a coordinate pair respectively. The input will be terminated by a coordinate pair (0,0) and this should not be processed. The first co-ordinate pair indicates the position of the boat's starting point. The last coordinate pair indicates the position of the destination rigs. All other points indicate the position of various rigs in the sea in a random order.
Output
Your program should print the minimum amount of food required to reach the destination. If it is not possible to reach destination, then the program should print -1.
Samples
Sample Input 1:
250 20 30 -1
10 -20
-10 5
30 15
15 35
0 0
Output 1:
111
Sample Input 2:
300 15 20 30 -1
10 -20
-10 5
30 15
-30 45
0 0
Output 2:
807
Sample Input 3:
150 20 30 -1
1 1
100 100
0 0
Output 3:
-1
One of the cherished customs of my childhood was choosing up sides for a cricket game. We did it this way: The two bullies of our gully would appoint themselves captains of the opposing teams, and then they would take turns picking other players. On each round, a captain would choose the most capable (or, towards the end, the least inept) player from the pool of remaining candidates, until everyone present had been assigned to one side or the other. The aim of this ritual was to produce two evenly matched teams and, along the way, to remind each of us of our precise ranking in the neighbourhood pecking order.
We all believed this was the fairest process, but does it ensure the fairest selection of players with evenly matched teams? We believed so, but then there were times when, as the game progressed we realized that the other team was stronger than ours and may be an exchange of a couple of players between the teams would have made them balanced. That scope of improvement seemed to be there...
Here, we need to find a way to create two evenly balanced teams for any game(or as evenly balanced as possible considering the strength of each player). A set of players must be divided into two teams. Each player must be on one team or the other; the number of player on the two teams must not differ by more than 1; each player will have a skill-point associated with him. The total skill-points of the players on each team should be as nearly equal as possible.(The absolute difference of the sum of skill-points of players in each team should be the least).
Input:
The first line of input shall contain N, the total number of players. N lines will follow with the first line giving the skill-point of person 1; the second line, the skill-point of person 2; and so on. Each skill-point shall be an integer between 1 and 450. There shall be at most 100 players in all.
Output:
Your output should be a single line containing 2 numbers: the total skill-points of the players on one team, and the total skill-points of the players on the other team. Print the smaller sum first.
Sample Input 1:
3
90
200
100
Output 1:
190 200
Sample Input 2:
10
2
3
10
5
8
9
7
3
5
2
Output 2:
27 27
Sample Input 3:
10
1
1
1
1
1
1
1
1
1
9
Output 3:
5 13
Sample Input 4:
8
87
100
28
67
68
41
67
1
Output 4:
229 230
Discuss the strategies of how would you check if two folders are in sync or not.(should contain the same files).
Alternative ways and mostly a discussion kind of question
Convert a binary search tree to a circular sorted linked list. The highest valued node should point to the lowest valued node at each step.
Test a function that sorts a linked list. You have two pointers head which is the original unsorted list and head1 which is said to be the sorted linked list. Return true if head1 did the sorting correctly and return false if not.
bool testlinkedlistsort(Node *head,Node *head1)I got the solution correct but messed it up while writing it over the white board :|
Given a number check whether it is equal to its sum of its factors or not (excluding the number itself)
The following code is the real code. Try to implement bridge design pattern. Question:
1) Please check if the code has problem?
2) Do you need to delete the ri and sr object? If yes, how?
#include <stdio.h>
class shape_Impl
{
public:
virtual int area()=0;
};
class RectImpl:public shape_Impl
{
int length;
int width;
public:
RectImpl(int l=0, int w=0):length(l), width(w){};
~RectImpl(){};
virtual int area() {return length * width;};
};
class shape
{
public:
shape(shape_Impl * imp) { Impl=imp;};
~shape() {delete Impl;};
int area(){return Impl->area();};
private:
shape_Impl *Impl;
};
int main()
{
shape_Impl* ri = new RectImpl(100, 100);
shape *sr = new shape(ri);
printf ("area: %d\n\n\n\n\n\n", sr->area());
delete ri;
delete sr;
return 0;
}What are the advantages of using spring?
Design an inventory tracking system using database tables. Customers, inventory, and orders are tracked.
Then, write a query to find an order when you only have a lastname
What is static method? What is a static initializer?
When would you use an interface vs. abstract class?
Explain the differences between HashTable and HashMap?
to print
*
*
**
**
***
***
****
****
*****
*****
#include<stdio.h>
void main()
{
int n,j,k,l,i;
printf("enter the number");
scanf("%d",&n);
for (i = 1; i <= n; i++)
{
for (j = 1; j <= 2; j++)
{
for (l = n; l > i; l--)
{
printf(" ");
}
for (k = 1; k <= i; k++)
{
printf("*");
}
printf("\n");
}
}
getch();
}Find the median in B-tree of order 4? Note that as the tree has order 4, it is not a binary tree.
Implement a double linked list using a single linked list. You have given only data and one pointer in struct node { int data, struct node *ptr}.
You should be able to traverse in both directions.
Why should we hire you?
Compute the square root of a function
You are given a threaded binary tree where each node of a tree points to some node to the right of it in in-order traversal. Given such tree, check whether each thread pointer of the node in a tree satisfies this condition( i.e check whether if thread pointer is pointing to node that is on the right side in in-order traversal). If not make that pointer NULL else leave it.
Each node has only three pointers pointing to left, right nodes and other the thread pointer. Space and Time constraint has to be considered while designing it.
shuffle an array of size n such that each element has 1/n probability to remain in its original spot. The best solution has O(n) complexity.
int getNthNonZeroElement(vector<int> & elements, int n) {
vector<int>::iterator i;
int count;
for (i = elements.begin(); i < elements.end(); i++) {
if ((*i) != 0) {
if (count == n) {
return (*i);
}
count++;
}
}
return -1;
}
The above code should return the nth non-zero element. For example, given vector v = [0, 8, 6, 0, 9, 7,20], should return 9 if n pass-in is 3;
Question: optimizing it.
My answer:
int getNthNonZeroElement(vector<int> & elements, int n) {
vector<int>::iterator i;
for (i = elements.begin(); i < elements.end(); i++) {
n -= ((*i) != 0);
if (n == 0) return (*i);
}
return -1;
}
btw, the original question should init count = 0
Write code to print out a binary tree so that each depth is printed on its own line. The spacing doesn't need to be correct, but the items within a depth must be in order and on a single line.
1
/ \
2 3
/ \
4 5
\
7
1
2 3
4 5
7
When to use composition and when to use inheritance. Explain with example. Do interfaces have an advantage over inheritance?
Given two arrays (of numbers), how can you find the common elements between the two arrays? What is the complexity? Will the complexity change is one array is much larger than the other?
Given a point how can you tell if it is inside a circle?
Tell me about one challenging project you did in industry/college
What are the differences between Java and C++? List as many as possible.
What is a join? What are the kinds of joins?
What does 'static' keyword do? Given a function as follows:
int foo() {
static int i;
return i++;
}
What is the value of i, if foo is called twice?
Should you make any changes if it is a multithreaded program?
What do you know about Bloomberg?
How would you implement phone book (data structure, time complexity etc.)? Given two names, find all the names and their phone numbers between them (sorted order). Will you change your data structure now? What are the time complexities now?
You are given a convex polygon and an additional point. You know the x and y co-ordinates of all vertices of the polygon and the point. Find if the point is one of the vertices of the polygon in O(log N) time.
Convert an integer to a string
You have a stack that is accessed by multiple threads simultaneously and you wish to synchronize access. You do not want to use locking to implement synchronization. Implement a thread-safe version of the stack.
Given an inorder and preorder traversal of a tree construct the tree
Find the n-th neighbor of all nodes in an undirected graph. Can you use the same algorithm for digraph? If not, why and what needs to be changed?
Design testcases for the strcpy function.
// Takes two null terminated strings
// and copies the chars in src onto dest
// including the null character.
strcpy(char *dest, char *src);How will u find the min element in the stack with O(1) . Space constraint also has to be considered while designing it .
Write a function to convert a number to Roman numeral.
Write a function to find the longest path of a tree
code to replace multiple spaces in string with a single space.
Explain Virtual functions. Explain with code why virtual functions are useful. why would you use a const function?
Why might quick sort might be better than merge sort.
What are the pros and cons of hash map and tree map?
Pick two data structures to use for implementing a Map.
* Describe lookup, insert, & delete operations.
* Give time & space complexity for each.
* Give pros & cons for each.
what every one knows is one Fibonacci series which adds the previous 2 numbers i.e fib(n) = fib(n-1)+ fib(n-2). but there many Fibonacci series which adds the previous 2 numbers, previous 3 numbers and so on. so write a function fib(n,k) which gives you first n numbers of a Fibonacci series and k is the number of previous numbers you have to add ex. for fib(n,3) you have to add fib(n-1)+ fib(n-2)+ fib(n-3).
In binary search we have two comparisons one for greater than and other for less
than the mid value. Optimize so that we need to check only once
You have N computers and [Ca, Cb] means a is connected to b and this
connectivity is symmetric and transitive. then write a program which checks that
all computers are interconnected and talk two each other
Given a problem scenario, write a program to output the total cost of solving that scenario. Given you have to construct house ( Senario ). And given all the factors that go into making the house, write a program that takes all parameters and outputs the total cost.
- Remember to do input type checking.
- Remember to make it optimized.
Get familiar with Intersystems CACHE. That is the best way to impress them. Read about CACHE and how it works. Read about Intersystems and their product CACHE( Worlds fastest database ).
READ about MIIS
There will be rapid fire questions. They are easy but make sure you do them as fast as possible.
there is 10 seconds per question.
Given a password in number : Write an algorithm to print all possible combinations of that password.
Hint:
- Try from to go from all possible combinations of lower bound to the valid upper bounds
From a given string, replace all instances of 'a' with 'one' and 'A' with 'ONE'.
Example Input:
" A boy is playing in a garden"
Example Output:
" ONE boy is playing in one garden"
-- Not that 'A' and 'a' are to be replaced only when they are single characters, not as part of another word.
Write a software to print triangle made of *s. Given the height and width of Triangles in terms of number of stars. like to output
*
* *
* * *
given you have to use 3 stars or the height is 3 stars.
Give an string, return the first non-repetitive character.
Code a function to shuffle a pack of cards
Given an integer array {1, -20, 29, 9, 1, 100, ..., 29), please return the index of the first non-repetitive element in the array.
Manager mentioned that HashTable was allowed.
How was your overall experience working at your last job?
What was the software engineering process at your last job?
Describe the different programming languages you have used.
Who are virus writers? Why do they write viruses?
How can a virtual memory environment be implemented to run multiple programs to prevent one program from accessing another program's memory space? Is the solution viable?
If you were designing new anti-virus technology, what would you implement?
How can a virtual OS can be compromised?
What sort of test setup would you require for understanding a virus?
What sort of behavioral patterns would you be looking at when designing a behavioral engine? What is the difference between a heuristical and a behavioral engine?
What are the characteristics that you look for in an anti-virus engine?
Can Linux be compromised? How secure is Linux? How would you compromise a *NIX system?
What is the difference between a heuristical and a behavioral engine?
What sort of behavioral patterns would you be looking at when designing a behavioral engine?
What are the characteristics that you look for in an anti-virus engine?
Can Linux be compromised? How secure is Linux? How would you compromise a *NIX system?
Describe your experiences using different anti-virus technologies.
Have you had any experience with assembly languages, particularly ASM?
Can a 32-bit PE execute on a 16-bit DOS? If not how will DOS determine that?
How is COM and SYS files infected?
Please explain the Windows PE executable standard and how a virus infects it.
What are some of the short comings in your role as a researcher?
What makes you a good researcher?
Describe the concept behind your current software projects.
What would make you an effective Virus Researcher?
What is a fact table and dimension table?
How would you eliminate duplicates in a linked list(singly) without using extra memory. You can use new variables for storing pointers but cannot go on to have a pointer for each node in the list.
- The values in the node are unicode characters.
- for eg: a->b->c->a->d->NULL
should be transformed to:
a->b->c->d->NULL
Write the function Itoa. This is the most common question asked.
You have an arbitrary sequence of space separated characters. Example, "a bc defga dcbaifk". Generate a new sequence with "(" and ")" added before and after the characters. The space should be eliminated.
You have a rectangle a and b. Determine if the two rectangles overlap. That is atleast some part of either rectangle should be within the other.
In a sequence of numbers 1..n, two numbers are missing. How will you find the two numbers.
In a given text file, replace all instances of "a savings of X%" with "(X% off)", where 'X' represents an actual percentage.
Given a CD changer which has hundreds of slots arranged as a circle to hold CDs. Some of them are empty. The changer has three operations. Rotate to a slot, load CD in the current slot, unload CD to an empty slot. Each operation may take seconds. Each CD have multiple tracks.
Implement a shuffle function that play all tracks on all CDs randomly. The requirement is a track cannot be play twice unless all songs have been played once.
I initially proposed to pre-process all CDs to know how many songs are there in total, then pick them randomly. But the interviewer told me that preprocessing may take several minutes, which is not acceptable. He expects a waiting time in seconds between each song. I was stuck in how to implement such randomness given the delay constraint...
Write a function that, given a binary search tree and a value, will find the next biggest node value in the tree
Write a function that takes as input two integer arrays of length n, input and index, and generates a third array, result, such that:
result[i] = product of everything in input except input[index[i]]
IMPORTANT: Your algorithm must run in linear time.
All Google search queries from all over the world are logged into a file.Now this file has billions of search queries in all languages which are interleaved.
Select 1 million Hindi queries from this file, such that all the Hindi entries in the file have equal probability of getting picked.
1. 2 huge files A and B are in sorted order. Make a combined file C which contains the total sorted order.
2. Extrapolate this to 1000s of sorted files containing millions of entries. Generate the combined sorted file as output
A company has decided to increase salary of all the employees. These employees are divided into 3 categaries: A B C. The people in C category gets N percentage increase.The people in B category gets 2*N percentage increase.The people in A category gets 3*N percentage increase. The minimum increase should be atleast 1% and no matter what the percent be the maximum increase should not increase $75000. Write a function which takes appropriate input and calculates the increase and updated salary. Print the increase for the employee and the return the updated salary.
There is a security keypad at the entrance of a building. It has 9 numbers 1 - 9 in a 3x3 matrix format.
1 2 3
4 5 6
7 8 9
The security has decided to allow one digit error for a person but that digit should be horizontal or vertical. Example: for 5 the user is allowed to enter 2, 4, 6, 8 or for 4 the user is allowed to enter 1, 5, 7.
IF the security code to enter is 1478 and if the user enters 1178 he should be allowed.
Write a function to take security code from the user and print out if he should be allowed or not
Write a program to generate all prime numbers from 2 to N for any N value
How can deadlock be detected and prevented in practical scenarios?
Suppose you have below line in your file
foo (bar ( new Point(x, graph.getY()) ));
write a regular expression to convert it to below format. I want to see space before and after bracket
foo ( bar ( new Point ( x, graph.getY ( ) ) ) ) ;
Write a function to identify if an integer has the same value when reversed (i.e flipped over. 6 when reversed will be 9).
For ex : the method should return true for the following integers
818
1691
88
but should return false for
8018
212
write a sql to find all the duplicate email address in a table which contains only one column "email"
Write a program to reverse a string and use it as a subroutine to reverse each word in a line
Write a program to evaluate a simple mathematical expression like 4 + 2*a/b - 3
Write a program to evaluate a simple mathmatical expression like 4 + 2*a/b - 3
Write a progam to rotate a matrix by 90 degrees.
Given an array of integers, write a function to find the 2nd max value. Write test cases.
There is a table with 3 columns. Test ( Id, Col1, Col2) . Id column is identifier. Col1 and Col2 are varchar type. How will you insert N records in to the table with time complexity less than O(N)???
Write a program to exchange the integers in a matrix along the non secondary diagonal?
Given arrays A and B, write a program to create an array C which contains all the elements in A and not in B (eg, A - B)
Write the function for changing a number from hexadecimal to integer htoi(s)?
How would you implement a string matching algorithm that supports partial match and also outputs a score for each match?
1. What does the 'final' key word do in Java?
2. Does C++ provide similar machanism? If not, how would you implement it?
Do you know what a mutex is? Explain how it works.
1. Do you know what a singleton is? Explain.
2. How do you make it thread-safe?
1. What's the difference between a pointer and a reference?
2. What's the difference between a class and a struct?
3. How do you allocate memory in C++? What's the difference between malloc and new?
Create all possible strings from a given number : 1800-WALMART
where WALMART :
W=9 A=2 L=5 A =2 R=7 T=8
9 on phone corresponds to WXYZ
2 corresponds to ABC
You need to create all possible strings out of these numbers.
Given two string str1 and str2, find all occurrences of str2 in str1.
The questions is as such pretty simple but the interviewer wanted me to use better than O(m.n) algorithm. I mentioned that we could use Suffix trees, and few other algorithms (http://www-igm.univ-mlv.fr/~lecroq/string/).
You must prepare questions with all string patterns.
Implement a search function which returns all the strings which contains the entered search string on a CellPhone
How to implement c++'s class's constructor using the struct in c?
What is the difference between pass by value and pass by reference?
What are abstract data types?
Char a[]=”abc” , char *a=”abc”; sizeof both? Where is “abc ” stored and whr is a and *a stored?
What is the difference between c and c++?
What is a race condition?
What is a deadlock and how do you avoid it?
What is the difference between thread and process?
How is heap used? What is heap fragmentation?.. Suppose there is memory available in heap but it cannot allocated - why?
What is static?
What is a variable and where is it stored?
Second Round
=============
How do you know if a number is Odd or Even?
Write a program to reverse a string and reverse words in a string
How can u swap 2 variables without using temp variable (XOR)
Char abc[10] ;
Strncpy(abc,”abcdefghijklmn”,10);
What r the data types and values of below
Abc
*abc
Abc[5]
Abc+4
&abc[5]
(*abc)+15
Float j=20.5 int i=20
If we say i+j , wat will be value of it..How the compiler treats it
File
Void settime(char* buf); //its defined in some other module
Static char* gettime()
{
Char buf[80];
Settime(buf);
Return buf;
}
Int main()
{
Char *D= gettime();
Fprintf(stdout,d);
}
Wat is wrong wth this code… It compiles properly… whr exactly is the problem…
Draw stack for both functions… How n whn stack frame gets overwritten?
What is the problem if we make buf static instead of local..
If it’s a multithreaded , wats the problem?
If u r using mutex whr exactly u wil lock the code?
There is file containing lots of words… ex A Novel . How would find the 25 most occurred words from it…
What is a pointer?
what is Turbo JAVA ??
The interviewer was asking me
Suppose there are only 1000 frond-end servers. To handle 1 million concurrent users, how would you architect those front-end servers?
How would you find an element in a sorted array (but the array is unbounded). 'Unbounded' means the array is not pre-filled but rather getting filled as data flows in.
Prove that 2^(2n) = O( 2^(2n) )
^ = power of
There are two linked lists which converge at one point. Return the 1st node at which they converge
[__]-->[__]-->[__]-->
[__]-->[__]
[__]-->Hope my diagram is understandable
You are creating a calculator for a second grader kids.
Write a function:
int Calculate(char *in)
where char *in is a string that contains an expression like: "1+2" or "-234334-345345" and you return the results accordingly. It is given that there would be two operands and an operator between them.
A binary tree contain integer values (both positive and negative) in its data field. Given a number N, find a path from root to leaf which sums to N.
bool ContainsSum(btree *root, int N)
It was simple. By doing a iterative pre-order traversal, and keeping tab of sum of elements, we can easily determine if sum of elements from root to any of the leaves is equals to N.
This problem is called Maximum contiguous sub sequence sum problem. I have been asked this question more than once at different interviews at Microsoft.
Given an array which can contain both positive and negative numbers, find the maximum contiguous sub sequence sum.
For example in an array = {2, -3, 4, -5, 6, -3, 8}, it should return 11.
Here was my solution.
maxsofar = 0
maxendinghere = 0
for i = [0, n)
/* invariant: maxendinghere and maxsofar are accurate
are accurate for x[0..i-1] */
maxendinghere = max(maxendinghere + x[i], 0)
maxsofar = max(maxsofar, maxendinghere)Given a set of points in a co-ordinate plane, how can you form a spiral??
There is a binary tree as below
1
2 3
4 5 6 7
8 9
10
given 2 elements say 5, 10 you need to find the common ancestor i., 2 inthis case. how will you go about it. ?
You have been given a sorted array which has been rotated unknown number of times.
For example: 7 6 5 1 2 3 4
Find the number of times it is rotated. Your algorithm should be less than O(n).
Follow up questions: Test on the following input.
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 1 1 1 1 1....10^10 times 1.
He wanted a foolproof algorithm that will not break on these stress cases. It was for Windows Manageability Group.
What are the advantages of Java over c++ and vice versa
Convert an integer into word. Example->1264 is One Thousand two hundred and sixty four. Corner cases are important. Integers are in the range 0-99999
How would you design a stapler for a blind person?
What is multiple inheritance?Why does Java not have it?How can we implement it in Java
What is JIT?
what is running time sieve algorithm for calculating prime number and why is it faster than the normal algorithm?
An AVL-tree is defined to be a binary tree that satisfies the property that for any node X, the depths of the left and right subtrees of X differ by at most one. Let M(n) denote the minimum number of nodes in an AVL-tree of depth n.
Q: show that M(0)=1, M(1)=2, and M(n)=1+M(n-1)+M(n-2), for n>=2
Q: prove by induction that M(n)= f<n+2>-1, for all n>=0, where f<0>=f<1>=1, f<n>=f<n-1>+f<n-2> are the fibonacci numbers.
show that 2^n is O(n!)
! = factorial
2^n = 2 to the power n
Why does java allow only one public class in one .java file?
What is the difference betn hashmap and hashset?
Can we call non static function from within static function?
String a="abhay"
String b="deol"
System.out.println(a+b);
======================
String a=new String("abhay");
String b=new String ("deol");
System.out.println(a+b);
========================
Which is more efficient? why?
Can we call non static function from within static function?
Difference betn abstract class and interface
Consider an array of positive and negative integers. We want to
find a slice of this array (i.e. a sub‐array of consecutive elements) with at least two
elements, such that the sum of the elements in this slice is equal to 0. The size of the
slice can be anything (i.e. from 2 up to the length of the original array), and we don't
care about finding the first, last, shortest, or longest slice, we just want a slice.
Example: from [2,3,-1,2,-4] we would like to find the slice [3,-1,2,-4], where 3 + (-1) + 2 (‐
4) = 0
If you were leading a team, how would you improve productivity?
You have a piece of code that randomly crashes. How will correct the error
Failed on 3rd phone interview on this question:
Given text, count the words inside.
This sounds a simple question at first so I finished and emailed the code within 5 mins; however the interviewer reminded ".", ",", "?" could also be separator, plus number like "123,456,789.012" where '.'/',' not considered as separator... asked to mail the complete code within 30 mins which I did with the code I'm not very satisfied.
The question is more about requirement and definition.
E.g. how many words in the string below?
"ab $2,300.58?2,,300.58 123?.235"
During interview, there is no time to collect all the requirement such as "give me the list of chars that could be separator", but I could give a nice algorithm without all clear definitions.
Any thoughts?
How do you use the Standard Template Library's std::sort() algorithm to sort an array declared as: int v[1000];?
class Parent{};
class Child::public Parent{};
Child*c=new Child;
Parent*p=c;
What needs to be added to the last line of the above sample code in order for the initialization of variable p to be legal? or it's legal?
std::vector<std::string>vs;
Referring to the container definition above, which one of the following lines of code fills vs with five strings containing the word "hello"?
You are given a lot of cuboid boxes with different length, breadth and height. You need to find the maximum subset which can fit into each other.
For example:
If Box A has LBH as 7 8 9
If Box B has LBH as 5 6 8
If Box C has LBH as 5 8 7
If Box D has LBH as 4 4 4
then answer is A,B,D
A box can fit into another only and only if all dimensions of that is less than the bigger box. Also Rotation of boxes is not possible.
done(int,int) throw(const char*,RangeErr);
What "done" does in this code?
SomeClass *ptr=SomeClass();
SomeClass *ptr=SomeClass;
What's difference,or it's the same?
how would you merge two sorted arrays provided not to use a third array nor u can allocate extra space. try to optimize the problem to the best. time complexity should be less than O(n^2)
How do you debug a process which is consuming 90% of CPU?
Given a set of coin denominators, find the minimum number of coins to give a certain amount of change.
How will you test a function that generates random numbers?
You are given an array which represents the heights of every bar of a histogram. Now all these bars are contiguous (juxtaposed wrt each other) and have the same width.
For Example, A={2,1,4} represents a histogram having 3 bars of height 2,1and 4 in that order. Now you need to find a rectangle in this histogram that has the maximum area.
See figure: http://www.ocf.berkeley.edu/~wwu/YaBBAttachments/hist_rect.gif
Time Complexity: O(n)
Space Complexity:O(1)
You are given a wooden log of length n. It has n+1 grooves marked on it from 0 to n. You are given an array containing numbers within the range of 1 to n-1. These elements of the array represents the points on the log at which u need to cut the wooden log. Now the cost of cutting a log is proportional to the length of the original log being cut.
Eg: n=15 and A={1,5,9}
Now when u make a cut at 1, the cost is n (the size of original log)
When u cut at 9, the cost will be n-1 as the length of the new original log is 1 to n i.e n-1
When u cut at 5, since 5 lies between 1 and 9 and the length of this log is 9-1=8, so the cost will be 8.
Hope the situation is clear now...
The question is: given the value of 'n' and the Array A containing the points at which u need to make a cut, find the order in which the cuts must be made in order to minimize the total cost of cutting the wooden log.
Find the length of a linked list which contains cycle.
Suppose you had an XML document which represented the contents of a tree. What would it look like? And how would you parse the XML document into a tree using C++?
You are given a NxN square board like chess. You are at the top left and your destination is the bottom right. There are many blocks on the board where you cannot go. At each step you can one block left, right, top, bottom but not diagonal. Write an algorithm to traverse from home to destination ? Print the path if you get to the destination or else return -1 if there is no legitimate path ?
Given three points of a triangle and one arbitrary point, determine whether that point lies inside, on or outside the traingle;
int isInside(Triangle, point);
/return 1 if inside
/return -1 if outside
/return 0 if on the traingle
Given two rectangles, find if there is an overlap between them ? rect1 is depicted as a set of two diagonally opposite points in a rectangle.
bool isOverlap(rect1, rect2);
typedef const char *month Table[3]
Create two monthTable arrays and initialize one of the two.
void f() throw (float)
{ throw 10.0f;
}
main()
{
try{
std::cout<<'A';
f()
std::cout<<'B';
}
catch(...){
std::cout<<'C';
}
return 0;
}
What's output?
Difference between Spinlock and Mutex. What will you use where?
I was given a simple code which had strUppr() function and asked to find the bugs in the code.
Bugs were related to following topics
1. Return value of the function was pointer to an array which is wrong.
2. A while loop with length of a string was written. There length of string was not considered till the end of the array.
3. A range of characters were compared. If (x>a && x<z). Here the bug is that a and z will not be considered.
How do you keep track of how many objects in given class exist?
template<class T1;class T2;class T3>
int Pr(T1 a,T2 b,T3 c)
{
return a*b*c;
}
What's wrong?
class x
{int i;
public:
int f() const;
};
{
return i++'
}
What's wrong with this code?
int x;
function()=x;
Is it legal or illegal code?Why?
int i=0'
while(i++<5)
{
std::cout<<++i<<std::end1;
}
How many lines produce this code?
struct A
{
int i,j;
public:
A(int ii,int jj):i(ii),j(ii){}
A(const A& a)
{
std::cout<<"("<<a.i<<","<<a.j<<")";
}
A& operator=(const A& a)
{
std::cout<<"["<<i<<","<<j<<"]";
return *this;
}
};
int main(void)
{
A x(1,2);
A y(3,4);
A z=(x=y);
return 0;
}
What is output?
class X
{
int a;
public:
X() {cout<<"X constructor was called"<<end1;}
X(int n) {cout<<"X(int) constructor was called"<<end1;}
~X() {cout<<"X destructor was called"<<end1;}
};
int main()
{
X x(3);
return 0;
}
Assuming all necessary header files , what is the output from the sample code above?
what's the trade-off of choosing a bigger or smaller cache
Consider the problem of building a wall out of 2×1 and 3×1 bricks (horizontal×vertical dimensions) such that, for extra strength, the gaps between horizontally-adjacent bricks never line up in consecutive layers, i.e. never form an internal "running crack". For example, the following 9×3 wall is not acceptable due to the internal running crack shown as a dotted line:
There are eight ways of forming a crack-free 9×3 wall, written W(9,3) = 8. Write a program to calculate W(32,10). To get you started, here are a few smaller values:
W(9, 3) = 8
W(18, 5) = 7958
1. If there is a set of numbers like: 1,0,0,0,1,1,0,0,1,1,1,0,0. How would you sort them?
Ans: Bucket sort or quick sort.
Write qick sort algo.
Given an array of positive and negative integers, re-arrange it so that you have postives on one end and negatives on the other, BUT retain the original order of appearance. For eg. 1, 7, -5, 9, -12, 15 => -5, -12, 1, 7, 9, 15
There are four different treasue chests each one containing gold, silver, brass and copper. There are 100 participants who try to find which chest contains which treasure.
In the end, it appears, that 23 have found none correctly, 58 have only 1 correct and 14 have 2 correct. How many have 3 correct? and how many have 4 correct?
what are fork exec,IPC
what is the drawback of strcpy,how can the drawback be fixed
What are threads,difference between thread and process,synchronization,what is the disadvantage of using threads?
Write a code to replace the word with another (please do not use the some built in function of a programming language)..
Write a program which asks user to input numbers and find the smallest even number and largest odd number from those numbers..
Implement a queue using a Stack? i know its possible with 2 stacks .. but the guy told me to use only a single stack..
Design a condo in any city that will give you the highest return on investment. Pick any city and money is not an object.
Given a string where there are numbers and some numbers are repeated, e.g. 13413124...,
design a data structure for it and the data structure should store positions of each number.
Given That One of the strings is very very long , and the other one could be of various sizes. Windowing will result in O(N+M) solution but could it be better? May be NlogM or even better?
Given two sequences of items, find the items whose absolute number increases or decreases the most when comparing one sequence with the other by reading the sequence only once.
How could you distinguish web pages which Koreans or Japanese read?
A river separates two banks, there are 3 men and 3 lions on one side that need to be taken across using a boat that can carry 2 entities at a time(irrespective of being a lion and man), subject to the condition that at no point can you have more number of lions than men on any bank, as then the lions would eat the man/men. Solve the puzzle. Then code it to make it a generic program that solves the puzzle for X men and Y lions.
3-3 is easy, generalization is a bit problematic.
Given an array of red, green and blue balls arrange them in groups of all red together, greens together and blue together. Do in a single scan of the array.
This is same as You have an array containing only '0's, '1's and '2's. Club same items together in single scan.
Efficiently implement 3 stacks in a single array.
Code a fibonnaci sequence.
There is a portal with two billion users registered. If you store all the 2 billion users in a conventional databases it will take more time to retrieve the data about a particular user when that user tries to login. How do you handle this situation to make sure that the user gets the response quickly.
Given a stack and an input string of 1234.At any point you can do anyone of
the follow
i. take the next input symbol and Enque.ii. you can pop as many as you can. When ever youpop an element it will be printed (you cannot pop from an empty stack)
Give an example of one permutation that this data structure cannot generate.
For Example:1234 is input.First push all 1,2,3,4 on to stack and pop all. output will be 4321.
It means that this data structure can generate 4321.
Given n non overlapping intervals and an element. Find the interval into which this element falls.
Worst case is take all intervals one at a time and see whether the element lies in the interval or not.It will take O(n). So please give a solution that will do better than O(n).
Now given that the n intervals are overlapping then how do you solve? The interviewer was concentrating more on the complexities (running, memory ..)
Given two int arrays A and B containing keys of binary tree. Is it possible for both the array elements to form identical binary tree in any combination or permutation .State the conditions .
A kidnaper wishes to write a ransom note using letters from a magazine article. You are given with the ransom note and magazine article find whether kidnaper can write a note using the article or not.
I was supposed to write a bug free code for thin in O(n+m) time complexity, O(1) space complexity.
There are two rabbits: Rabit A and Rabit B. Both of them run a 100 m race . When rabbit A finishes the race rabbit B is at 90 m mark. They run at constant speed. Without calculating time , speed or distance , by just analyzing the given data tell when A starts from 10 m behind the 0 m mark (110 m run for A) and B starts at 0 mark only , who wins and why ?
Given a n-ary tree of resources arranged hierarchically. A process needs to lock a resource node in order to use it. But,
A node cannot be locked if any of its descendant or ancestor is locked.
I was supposed to
-> write the structure of node
-> write codes for
-> islock()- returns true if a given node is locked and false if it is not
-> lock()- locks the given node if possible and updates lock information
-> unlock()- unlocks the node and updates information.
Codes should be :
Islock –O(1)
Lock()- O(log n)
unLock()- O(log n)
Question involved indexing from DBMS.
Given a set of attributes how will you improve the retrieval time for a query involving these attributes.
-> You are allowed to change the physical storage
-> You can create index files
-> You need to minimize block accesses and memory used.
A string representation of a n-ary tree is given in the following format
(a(b(v)(w))(c(k(d)))(e))
This string can be interpreted as root followed by all its children enclosed in (). Every children is then represented in the same way as root.
Eg: In above string a is root. b,c,e are its children, while v and w are b's children and k is c's child which in turn is parent of d.
I was supposed to write a code for converting the string into the corresponding n-ary tree.
Given a string : abbbccddddeee
Encode it to : ab3c2d4e3
Write a program to do so and also write test cases for the same.
They asked about various storage class specifiers of C : static,register,extern
Their scope and existence during a program execution.
Write a code to check whether a number (int) is a palindrome or not. The code was supposed to be bug free and all exceptions handled. The code was supposed to return true if function worked properly and false if function created an error.
Int IS_Palindrom (int num, int *p)
{
}
return value conveys state of the function and *p contains result of the function.
Do you remember the name of the person you spoke to in the first round? Why do you think you are good for this role? How much do you expect to get paid - how much base/bonus? Where do you see yourself in 5 years? What do you think is the main difference between a life in academics versus a corporate life? Give an example where you had a deadline to meet (in a team situation) and how did you do in that situation?
What data structure do you prefer to use to implement a stack?
What do you understand by deadlock?
Difference between C-strings and string class in C++.
Write a code that displays the bit pattern corresponding to an unsigned decimal integer.
Reverse words in a string (e.g. |i||a|m|'\0'| ---->
|a|m||i|'\0'|).
Given a number (say, 7251), write a code to give the number of digits it has (i.e. 4 for 7251).
Given a set of points (x,y) on a 2D coord system, identify list of 2D coords that are of distance less than x units long.
Eg.
Let x = 1;
Given (0,0), (0,1), (1, 2), (4,6);
Return 1 -> (0,0), (0,1)
WAP for tic-tac-toe game and test it
Design an LCD for a cab.
Design an alarm clock for the blind. They asked how the person could identify the physical object.
Each interviewer had a copy of my resume and asked me specifically about a project they were interested.
What are the issues with putting an excel spreadsheet on the web ?
Implement a priority queue with a Double Linked List.
Design a tablet for a kitchen to aid in cooking ?
What did you do wrong in your life so far ? Do you regret it ?
1. Carefully see the following transition from one word to other-
PAN -> PEN -> MEN -> MET
Here each word is achieved by changing any one character in previous word. Now you are given with a Source word (PAN here) and a Destination word (MET here) and need to find out shortest transition chain following above rule using only meaningful words. Dictionary containing thousands of meaningful words is provided to you. WAP for this.
Write a code to calculate kth power of a matrix of size nxn. You can assume that matrix multiplication is O(n^3).
Write a code to remove the characters from string1 which are present in string2.
There is a circular table. You and your friend have infinite number of coins. Both of you place one coin in each turn on the table. Coin can be placed only in the empty space. Whoever places the last coin wins the game. If you are starting first, design a strategy so you will always win.
Given n strings. One string can be connected to other only if last letter of first string is same as first letter of second string. Like this all n strings are connected. Find whether it is possible to form a chain of these strings i.e is it possible to connect all the strings in such a way that all the strings are connected and each string occurs exactly once.
Hint: Hamiltonian path
Write a code to reverse alternate nodes in a link list.
Design a deck of cards.
how do you compute the number of digit after . in floating point number.
e.g. if given 3.554 output=3
for 43.000 output=0
Write the test cases for an algorithm that shuffles 52 cards.
A sorted array, with over a million elements in it, is rotated clockwise. Find out the index where the sorted list starts.
A program has a bug. How would you debug it?
Explain how you would test a car.
Design a car renting system, including reserving a car, checking in and checking out. consider all the cases: reserve a car, then check out successfully; reserve a car, but the car is sold out before you check out...
Add the test cases.
Why does destructor in base class need to be declare virtual?
What is name hiding?
Given a string The software must print all its valid anagrams. i.e if Input is 'dog' it must print 'dog' and 'god'.
On probing He told we can make use of a function isword() to find if string is in dictionary.
Divide a list of numbers into group of consecutive numbers but their original order should be preserved?
e.g.
8,2,4,7,1,0,3,6
2,4,1,0,3 and 8,7,6
obviously in shortest time and space.
How do you represent the following expression in "class design": (5*3)+(4/2) ? How would an algorithm that computes the value of this expression work?
Question about java Generics. What it is? Functions and Generics questions. Best if you study it well.
Given 1) an int[] array and 2) an int value, how do i find out which two elements in the array add up to the value given? What is the speed of your algorithm? Can it be done faster?
How do you model an elevator in OOP? Extremely vague question on purpose. He wanted me to talk about the algorithm of elevator selecting which floors to go to based on the buttons pushed inside and outside elevator. Kept on asking followup questions. Prepare by thinking about how the algorithm for elevator works.
There are 9 marbles. 8 of them are of equal weight, 1 is not. You are given a weighing scale. How do you find out which one is has the different weight? Is there a faster solution? What is the speed of your solution?
Given a string and print the words which have the same exact letters. Space is the only seperator.
For example, abc bbe bca derwe eeb
it will print abc bca.
abc bbe abcd derwe eeb will print nothing.
Given two lists l1,l2, show how to merge them in
O(1) time. The data structures for the lists depends on how you design it.
Find the sum of all prime number less than N.
If you have a lot of memory (an array of integer), how you are going to use that to optimize your algorithm.
1) Suppse you have ClassA and ClassB
One way to create an instance of ClassB in ClassA is
Class A
{
ClassB b = new ClassB();
}
What are the other ways to do it?
Write a method in C to reverse a linked list.
Implement a class using singleton pattern
if you have a phone number in thousands of files in a directory, how would you go about removing only the phone number from each file (not all files have the number)
if you have 50 white beads and 50 black beads and you MUST put all of the beads into two bins (50 beads in each), how do you maximize your chance of choosing a white bead (from either bin)
find a duplicate number in an array
write a string compression algorithm that takes strings like "kitten" and returns "k4n"
if you had an array of numbers from 0 to 1 million, how would you figure out the missing number
write syntactically correct code for a power function that takes two arguments, x and y, and computers x^y
Implement enqueue and dequeue for a stack.
class stack
{
push(int i)
pop()
count() : count the number of elements in stack
} is given.
Explain how memory leaks occur in java. How would you check for them?
Write a method to print all valid anagrams of a string
Write a method to check if a number is power of 2
Explain how polymorphism works.
Design spam filter
How would you save a graph to a database?
Compare and contrast SAX and DOM
A semi-connected graph is a graph that for each pair of vertices u,v, there is either a path from u to v or a path from v to u. Give an algorithm to test if a graph is semi-connected.
Serialize a binary tree to a linked list.
Detect a cycle in graph(DFS)
Count number of bits and asked me later to do it in O(1)
Virtual functions and vtable...
What happens when a Constructor gives a call to a virtual functions
What if it is a pure virtual function
In an unending stream of numbers, pick a number with equal probability.
Write code and test cases for traversing a linked list.
Imagine you are writing a webcrawler. Write an algorithm to find the page most linked-to page on each website.
Design a stack of elevators.
Write code and test cases for reversing a C-style string.
In MS Excel, the column numbers are named as A, B, C, ......, Z. If you go beyond this 'Z' column you will encounter AA-->AZ, BA-->BZ, .... ZA-->ZZ then AAA-->AAZ, ABA-->ABZ, ........ and you can imagine how long this sequence can go! The question was to write a function which takes in a positive integer and
returns the character set at that column. For example: if column number is 26 my function must return 'AA' (0-based index). I basically started looking for any specific pattern if I can find for how many columns names are 1 letter, 2 letter, etc. fortunately there's a pattern involved. I couldn't solve the question completely as we ran out of time but interviewer seemed satisfied as I started by looking for a pattern and not sat down to code without giving a thought.
Write a function int Compare_Strings(char* str1, char* str2){...} such that the function returns +1, -1 or 0 based on whether str1 is LEXICOGRAPHICALLY greater, smaller or equal to
str2; the comparison should be case-insensitive. For example: "abc" is smaller than "mno" as 'a's ASCII value is less than 'm's. However, "ABC" and "abc" are equal.
Also discuss the test-cases.
How many oranges/spheres (each of diameter 10 units) can you fit into a box with a size = 100 X 100 X 100 units.
There are hundred prisoners each standing in a column. Each one is given a hat and there are two possible colors of hat which are red and white. The 100th person can see the hats of 99 people in front of him and the 99th person can see 98 people in front of him but can't see his own and the previous hat. The number of hats aren't known and the hats are placed in random order. Starting with the 100th person, each person is asked what color hat they have. If they guess wrong, they die. Come up with a strategy such that maximum people are alive. How many people are alive? (Do not use probability constraint given)
given a directory tree, how can you find a subdirectory whose capacity is 100% full.
how can you periodically print the cpu usage of a given process id in Linux
Given a finite set of SSNs or ZIP code, what data structure do you use for storage.
How can you serialize a binary tree
Find intersection of two arrays
Design software for a restaurant
How can you provide redundancy in a mission critical application. - question related to H/A and load balancing.
Implement an LRU cache
Print all possible combinations of the word "amazon"
How would you know whether a website like gmail or yahoomail is reliable?
Define a two-dimensional boolean array. Minimize the memory allocated. Write a function to set a value to an element of this array.
Given a set S of n distinct numbers and a positive integer k <= n. Determine the k numbers in S that are closest to the median of S. Find an O(n) algorithm
Asked me to write a piece of code in Java to output a file in XML format, and then something about OOP (general stuff like polymorphism etc)
Lot of HR, tell me about yourself, what do you know about Bloomberg, things like that.
Overall atmosphere was very laid-back, but I was too nervous, it probably showed.
They work with a lot of legacy stuff, company ambiance is great, apart from the usual cubicle like environment.
Given an integer array A,
find the max item A[i].
A[i]=A[x]+A[y].
O(nlog(n)) or O(n^2)
Given 2 sorted arrays of n elements A,B. Find the k-th smallest element in the union of A and B in O(log k) time. You can assume that there are no duplicate elements
1) How would you serialize a BST .. He was looking for something like:
((10, 6, 12), (12, NULL, 15)) i.e.
(parent, left, right)
2) Write the recursive and the iterative algorithms for printing out N fibonacci numbers
3) Design a Parking lot using OOD
4) Given a number, how would you figure out the next prime number
5) Reverse a linked list using recursion
you have 625 balls on ground and infinite balls in a bag..
make a pyramid from this..
how many balls do you need..
tell structural analysis issues.
ASCII characters are stored as 1 byte and MSB is always 0 like for 'A' ascii code is 00001101..
but for a japanese letter it takes 2 bytes like for say japanese character * it will be b1b2.. two bytes but MSB digit is 1.
like for * 10001001-10111010 ...
make a backspace function for this..
write test cases.
two sorted array are given .. say A1 & A2.
A2 has space for all the elements of A1 .
now make a library function for finding the merged sorted array.
O(n) time
How do you perform binary search on a rotated sorted array?
eg., 75, 77, 85, 91, 10, 19, 26, 29, 33,45, 67
write a iterative function for postorder binary search tree traversal(little bit challenging??????????)
Convert string into new string e.g. "abcD"->"cdeF" and "plxY" -> "rnzA"
Bag A = 10 Red balls.
Bag B = 10 Green balls.
Shuffle bag A move three balls from A => B then
Shuffle bag B move three balls from B => A
Which bag is likely have more number of balls of other color.
Shuffle an array of 52 integers.
Test plan for "Search String" for notepad.
Given an array, find the first repeated number.
What do you understand by O(n)? Which grows faster, O(n^2) or O(4^(logn to the base 2)?
What is the default visibility of an instance variable in java? What is package visibility?
What is final, finalize and finally? Where do you use 'final' keyword. What is the effect of making a method final?
You have a huge file that contains 3 columns employee id, department id and salary. Give me the avg salary per department. I said I would use a hash table.
He asked what are the performance issues with this appraoch.
Then he said given that you have multiprocessor system available what can you do. I said we can open multiple filepointers for reading from different parts of the file and write each record into a hash table which is made thread safe. He said that would help only if the file is stored in different tracks.
Then he asked, for every record you are writing into the hashtable waiting for a lock on it and writing. This is very inefficient, tell me how you can make it more efficient. I said I will use a cache in each of the thread and write it out to the hashtable only when cache is full. He said that is a good solution.
Design a chess game.
The interviewer explained me the real world scenario of the blockbuster..
A location receives hundreds of copies of each film. They can be of multiple formats ( DVD,CD,Blu ray). We need to store the following information regarding the film: director, actress, rating. There are different genres possible. Action, drama etc. All the copies of a movie are placed under its shelf marked with its corresponding genre. All the movies of same genre are of the same cost. But the first time the movie arrives it stays as a different genre called "New RElease" and it is placed in a different location and priced differently. It stays that way for x number of days and after that it goes back to its corresponding genre.Each customer can take out any number of movies at a time. We need to store the due date for all those movies.
Design a software with class diagrams for this. This was asked in the first round telephonic interview.
why all of the following are considered as bad hash functions?
1. Random(0,N)
2. 2*n mod 31
3. n mod 15
4. n mod 31 + 2
Give correct reasons.
Given a n*m matrix having numbers such that each row and each column sorted. Now print the numbers in present in the matrix in sorted order..
ps: He gave me the hint as, we can rearrange the matrix.
Given 2 arrays. a1 of length l1 containing numbers in sorted order. a2 having 2 parts first part(which comes at top) of length l2 containting numbers in sorted order, second part of length l1 is empty(which is at the bottom). Now merge the elements in both the arrays and write that to a2.
ps: dont do any initial adjustments like rearranging elements in any array(coz, i did the same in interview and he didnt accept my solution)
how can you efficiently implement the find and replace function for a string....
how do you test the validity of a sql query??????
For example, if there is a function isValidQuery(string query) it should return true if the query is valid else false....
Why use inner classes?
Given an array of integers where some numbers repeat 1 time, some numbers repeat 2 times and only one number repeats 3 times, how do you find the number that repeat 3 times.
I gave the hashmap solution. He was looking for a bitwise operator solution.
How do you implement the following feature which Amazon uses on its website?
"What Do Customers Ultimately Buy After Viewing This Item?"
81% buy this item
10% buy item B
9% buy item C
A number is called 'desirable' if all the digits are strictly ascending eg: 159 as 1<5<9. You know that your rival has a strictly numeric password that is 'desirable'. Your close ally has given you the number of digits (N) in your rival's password. WAP th\hjtat takes in 'N' as input and prints out all possible 'desirable' numbers that can be formed with N digits.
Explain in place merging of two sorted arrays?
Given a binary tree, prove that it is a BST(Binary search tree), without using inorder traversal either recursively or iteratively..?
Given a circle of radius R, take a point inside the circle.. now what is the probability that, this point is more nearer to the centre than to the circumference?
This question was asked in Microsoft interview. Write a program to determine whether it is a good string or bad string.
For ex: {abcdteeh} - good string
(bans{xyzhs}aj) - good string
}this{ - bad string
{abs{jeu} - bad string
If the string contains the equal no. of corresponding braces, brackets and parathesis. Moreover, if the string is {adbc(xyz}the) bad string...
You should take all the possible scenorios and write an efficient code it.
Consider how the numbers on a mobile phone's keypad are mapped to letters. Given a number as the input, generate all possible alphabetical strings that it can represent.
What is the different between .a .o .out files?
What happens when u delete a null pointer?
char *p;
del *p;
*p=null;
del *p
What happens when u delete a pointer twice
del *p;
del *p;
What is this error called? How to avoid such double deletes?
Compare and contrast dynamic array & linked list
Why is malloc preferred over calloc?
How is the memory allocation done for a union?
What is the return type of constructor?
Why do we need abstract classes?
I had two phone interviews at Amazon.com. Got rejected after the second interview even though I thought I did very well (think I answered every question correctly!). I'm thinking it must be the economy :(
What is the complexity of operations in a binary search tree?
Explain how memory allocation works in C++. Where is the stack vs the heap used?
Explain how HTTP get/post method works.
Explain how to use servlets and JSP.
Write a method to reverse words of string.
What are the advantages and disadvantage of hashtable vs binary trees. When would you use it?
Implement an algorithm to generate all prime number from 1-100 in fastest and most efficient way
Design an algorithm, as well as the necessary data structures and algorithms, for valet parking to find parking spot. How would you charge?
What is Normalization? And what is First Norm Form:
Eliminate duplicative columns from the same table.
Create separate tables for each group of related data and identify each row with a unique column (the primary key).
What is the difference between C and C++? Compare and contrast the two.
Given location of huge number of points (you decide the data structure to represent them). Write a function that returns the number of points that are with distance D of a given point P.
Write function, complete with what data structures, function signature etc.
Question about Constructors, Destructors, Virtual functions, order in which these are called when creating objects, deleting objects etc.
Design a One shot timer library capable of supporting multiple times simultaneously. Cancel is also supported. Only ONE hardware timer register.So basically, a process/function can call SetTime(10) and it will get notified after 10 seconds. It can also say SetTime(2)... SetTime(7). Then it will get two notifications, one after 2 and one after 7. [SetTime returns a handle]
The process(s) can also issue a cancel. Cancel(handle), to cancel a specific timer they set.
The hardware timer registers, assume decrements by 1 every 1 second. So if you set it to 10, it will notify you after 10 seconds. Basically it interrupts, and lets say calls RegExpired(). You can Read/Write this register anytime very fast (uS).
The key here how you make use of this single register to support any number of timer events that applications/processes are demanding asynchronously.
Discuss the data structure you would use and implement it in C.
Make a nonblocking UART library given a underlying UART hardware, data registers and flags that mark end of transmission and stuff.
This is very common. Simply look for Software UART in embedded systems. Also uses some OS concepts like round-robin, preventing spin locks etc.
Print a Link list in reverse order.
Given: PrintReverse(List *head){}
Discuss Pros and cons of Inplace reversal, as compared to reversing by creating a new list. They were looking not only for Memory and Space, but also from a concurrency Point of View.
On campus Microsoft for SDET:
1. Why SDET ?
2. How do you approach a testing problem - Explain ?
How will you test a soda can?
You are given a set of reference files (.txt files). The files contain sentences in English language. You have to write a function to process these files. The input to the function is path to the files. Take each file, read each line and process it so that you get first word last, last word first and so on (reversing the order of the words) and send the words to a function that translates each word into Hebrew. Assume that you already have the function that translates to Hebrew. You just have to use it. Function prototype is not provided. You can make your assumptions.
Give the inorder,postorder& preorder forms of a tree in a single traversal
Given an n*n matrix A. Each row of the matrix and each column of the matrix is sorted.
Given a number S, you are required to find S in the matrix( report k, l such that A[k,l] = S) or conclude S is not in A.
How can you solve it in O(n)?
code a function that returns the nth fibnocci number... coded it the most efficient way by using 3 variable... Then the interviewer wrote the recursive form and asked me what are the pros and cons of your(iterative) approach and recursive approach.
REverse the words of a string.. Code it and write test cases.. Here many test cases failed ... Since I was able to point out myself what went wrong I think that covered up for the buggy code I wrote.
Tell me about yourself and briefly describe what is in your resume
Test a UI function that takes inputs from the keyboard keys 1,2,3,4,5,6,7,8,9,0,. and returns a valid mathematical value. Write different test cases for this function.
Given a canoe, what test cases would you write for it.
You have a coke machine that is spitting 2-3 coke cans a second. You have a requirement to test every coke can that comes out. What test cases will you automate?
He made me think for 15 mins to get all possible wired things that you can test.. and also how you can test...
This truly required a lot of thought .. In the end he was impressed ( lucky me :) )
You are a consulting company, that had done good once upon a time and now is in a almost bankrupt situation.
Then a big client comes and says that they wanted to code a distributed application using HTTP. You know that for the scenario the client is describing, SOAP would do a much better job. But the client is adamant at going with HTTP. What would you do?
How would you go about testing a pen? If you needed 10 weeks to test the pen comprehensively and you are 5 weeks into your work. Then they give another pen based on a new technology and ask you to test it along with the original pen within the remaining 5 weeks. What do you do?
a) you shout at management saying that this is crazy
b) You work overtime to complete the work
c) you inform the management that the time is not sufficient
I said a combination of b and c.
Given a string as input , say " ababcdcec", the output should be the number of times the character that has repeated the maximum. In the example a occurs twice, b occurs twice, c occurs thrice, d and e once each.. Thus the function should return 3.
Asked to write test cases for this.( wrote arnd 10 ) for which the interviewer said that the testcases are 80-90% compprehensive
Why Microsoft? Which is your technically most challenging project?
NOTE: These 2 questions were asked in every round of 5 onsite interview rounds
Convert a doubly linked list to a binary search tree in place.
divide an array of numbers into two set of numbers in such a way that difference in their sum of numbers is minimum.
in a given sorted array find two num whose difference is equal to a given number
in binary tree find two nodes whose sum is a given number in lg n time.
in a given array of numbers, find all the set of 2 or more numbers whose sum is a given number.
print the tree in level by level i new line????
When u use free() in C how would system now the limits of the memory block that should be freed?
How would u debug a process that is using 99% of CPU?
Types of polymorphism
you are given a binary tree....write a code that returns the leaf node
present at topmost level....
two leafs may be present at same level
(take care of this condition)
given a binary tree,find the distance between leftmost leaf
and right most leaf nodes. Leafs may be at any level...(Nice question)
design a searching algorithm in O(1)...No extra space.....
In a sorted array of 0's and 1's ,find the first occurrence of a 1 in it....
eg:
000111111111
must return 4
given a binary tree ,find the largest sub-tree which is a BST...(largest means subtree having largest no of nodes in it)...this is a wonderful question.....
What should not be done in an ISR (Interrupt Service Routine)?
In networking, explain how the ARP and DHCP protocols are used.
Other than virtual-physical mapping, what is the other functionality of MMU?
Asked abt Write-thru, write-back caches..when is a word evicted in write-back cache ?
What does appending 'static' to a global variable/function do?
Write the code for a change vending machine.
How was your experience? What went bad you did during the day?
Test blind windows.
Round 3:
Something about me.... My intership project...
This guy asked me twice if i know C#. I told me NO both of the times.
Q1. reverse the string. Example "This is test" to "sihT si tset".... key point here was do not assume that "space" is the onlu delimiter....ask this Question.
he again asked me if i know C#. this time I said if u can give me the class and its functions, I can try.
Then he gave be 2 DayTime objects and a random function... return the random date between these 2 dates.
First Interview at Redmond...Lunch Interview.. with SDET-II. half of that happened in his office, rest of it in the canteen
Why SDET?
Given an unsorted array, return the first repeadted integer? I gave him first the bitmap solution.. he said somebody has solved the same problem in the same way...:D... but there is more simpler solution. ... then i gave him the hasttable solution... then code it....later tested it.
Test a vending macine?
Few details about the project.
Over to lunch where he asked what challenging tasks you have faced? I kept him busy by asking lots of Q rather the other way round.
This is the phone interview. I was interviewing for SDET.
Why MS?
Why SDET?
Tell me something about youself?
Given a sorted LL, insert an element at a given position. Test it?
Do you have any questions for me.
My tip: Prepare well for the testing Q as the program is not so diffcult.
We have a 3d object reference. Find 20 most nearest object references? Consider you know all the object references? What if you knew the distance?
Design a deck of cards. What classes? functions? constructors? What functions can you add? Where would you add them. for eg shuffle and deal a card functions. What happens if we need only a particular sort of card eg spades? How would you handle multiple decks?
(believe me that was never ending discussion, finally it ended when i started crying :-)
Why are destructors important? Where are they not important?
What are Virtual function, why are they important? Where did you use them in your projects?
how to free memory allocated to an array with new function?
What's code coverage?
There are two collections of objects C1 and C2. C1 can be any thing - Flowers, Fruits, Foot Balls etc.. and C2 also same. How can you find out if C1 is a subset of C2 or C2 is a subset of C1 or both are equal? Provide algorithm, code and test cases.
The interviewer was expecting a linear algorithm - the algorithm with a time complexity of O(n)
What was the most difficult problem you solved so far?
How do you find out if a given string S1 is a substring of another string S2? Provide algorithm, code and test cases.
How big was the team during your Internship?
There is an array of 52 numbers ? How do you shuffle this array ? Whats the complexity of your algorithm ? What are the possible test cases ? How do you change the design and or code if this program is used by a house wife or casino?
What are the problems with User Interface Design in a project?
Do you prefer to work on the front end or back end of a product? What are the pros and cons of working on Front end and back end ?
What did you study? Tell me about your projects and thesis.
A good and challenging Series to solve
I need to find to the mathematical series for this one .
f(-9)=-49213156
f(-8)= -2448222
f(-7)=-141362
f(-6)= -9751
f(-5)= -839
f(-4)= -97
f(-3)= -16
f(-2)= -4
f(-1)= -1
f(1) = 1
f(2) = 0
f(3) = 8
f(4) = -47
f(5) = 503
f(6) = -6485
f(7) = 100898
f(8) =- 1835574
f(9) = 38270970
for both + ve and - ve numbers different series algo.
+ number input vary from 1 to 9
- number input vary from -1 to -9
Design a File system for windows or linux machine. Use OO concepts.
Reverse a string , . don't use any temp variable to store the string .
Identify the regular expression in a given string such that the pattern does not repeat. For example, to identify the pattern 'foo' only once in an input.
'jhkhfoojkkj' should be identified right
'kjhfooaaaaafoo' should not be
A person can take one or two steps at a time to reach a particular floor( say in a building). How many different ways can a person reach the nth floor?
Implement memcpy(void* src, void* dst, int len)
I was asked how to select M numbers from N existing numbers randomly and fairly (N>M). Example, assume that there are 10 numbers, you need to select 3 numbers from them randomly.
calculate how many days between two given date.
How to test a vendor machine, give me some test cases.
Minimum Common ancestor of given two values in the Binary tree
What is the difference between these two statements
void (*p) (void *a[],int n)
void *(*p[]) (void *a, int n)
how to test
HRESULT drawpoint(int x,int y, Color c)
given string
input1, input2, remove wherever the occurence of input2 in input1.
e.g:
input1: abcthabdtheshhtexyztheaaa
input2: the
will become abcthabdshhtexyzaaa
give the test cases.
Position is in London.
I had a telephone interview HR round - typical HR questions
1. Why are leaving the current role
2. What do you know about Bloomberg
3. Salary expectations
HR described about the role in detail and asked if any questions.
Implementation of Polymorphism in C++?
Difference between C# and Java?
Tell the 7 layers of the Networking Protocol Stack?
Difference between TCP and UDP?
given an array of positive numbers and negative numbers devise an algo to find max non-consecutive sum in that array.complexity should be in o(n).
what is segmentation fault? given an example of when seg fault would occur
Find first prime number greater than number given in input
Find all the prime factors of a number entered
Find the largest prime factor of a number
In your opinion, what is the most important part of a sale or sales process?
What would your previous boss say about you if I called him today?
How do you deal with rejection / failure / a lost sale?
What is your greatest professional strength? Conversely, what is your greatest professional weakness?
How have you used partners / vendors / the sales channel to help you in your sales in the past? Describe some of your relationships.
Tell me about the sale you are most proud of. Describe the sales process you went through.
What do YOU like about working here?
What do you know about our competition?
Why do you want to work here?
Describe a typical day for you in your last sales job.
A customer calls in who is very unhappy with you about a product they have ordered. What would you do?
Why do you like sales?
Tell me about a time when you failed. (Make sure your answer has a positive spin about you).
I previously carried a quota of X dollars, what sales goals are set for this position?
In my last job, I would call on my customers / prospects X # of times a week. What type of activity level are your reps attaining?
How to shuffle lines in a large file, which cannot fit into the memory. However, you are allow to use linux sort command. Any ideas?
How do you set a pixel in a monochrome screen of size 800 by 600. The pixels are stored in a 1 D array.
Find phone numbers in a directory containing some billions of files.
I just said use a regular expression, u can use it in grep or u can use it in sed type of scripting or u can write a Java/C++ program
Find the k max elements in an array of n
Ans: Keep a heap of k with min on top. If you find an element in the array which is greater than the mean, kick the mean out of the heap and heapify(re-heap)
The complexity is O(nlogk)
But coding a heap is difficult so I think in onsite if this question is asked better use an array instead of heap, so the complexity will be O(nk)
Design the datastructures for an online book reader system.
Last guy told me to design the T9 system, which is the predictive text system on cell phones. E.g type 49556 and get "hello" and also other words that matches 49556. More specifically, how do I store a text file containing a dictionary on a cell phone and efficiently read from it.
This guy asked me about my college, why I am here, what are my long term goals, etc. And then he asked supposed you're on the windows Vista team and there are 5 million programs we have to make sure it works for Vista, but we only have enough resources to test 5000 of them, how do you do it?
- This you just have to explain how statistics work and tackling a lot of work by splitting them up and categorizing them.
Give me the best way to multiply an integer by 3.5. There are many solutions to this but (x>>1)+x+(x<<1) is the best since it is least prone to overflowing.
Write a function to convert integers to roman numerals with 1=I, 5=V, 10=X, 100=C, 1003=M. E.g. 3999 = MMMCMXCIX
This was tougher than I thought.
How would you test a vending machine.
Given a 2 dimensional array of integers representing a tictactoe board, write a function to look for winners.
When would you use a hash table over a Binary Search Tree?
When to use and when not to use multi-threading and multi-processing? Which is better and when?
Where in memory are a program's static variables stored?
Advantages of const over #define. When to use which of them?
Q. There is a software for chess game and we need to test the following method:
boolean canMoveTo(int x, int y)
x and y are the coordinates of the chess board and it returns true/false whether the piece can move to that position or not. We need to test this method for a pawn piece and you can set up the board any way you like prior to running a test case. Source code is not provided
Q2. Design a software for valet parking
What are threads and why use multithreading? Things which we have to be carefull with when using threading.
1) Write a function which determines wheather in given array there is a sequence of n or more elements, which have the same value. Example:
n = 3, input[] = { 1,1,1,2,3,4,5 } gives true;
n = 2, input[] = { 5,1,2,2,2,4,5 } gives true;
n = 3, input[] = { 5,2,2,3,2,5,5 } gives false;
2) Write a function which determines, wheather the array is a mirror - reflection - like. Example:
input[] = {1,2,3,2,1} gives true
input[] = {1,2,3,3,2,1} gives true.
Reverse a linked list iteratively, do it first with single pointers and then do it again with double pointers. Now do it again recursively but not tail-recursive, and then do it again tail-recursively. What do you do if it has a loop?
A String as given as input in the form of Hex Decimal format and you need to print the ASCII format.
Before starting the algorithm, what are the question do you have in your mind?
write a code to delete any node in a link list. with all test cases and boundary conditions
-u r given a disk. half black half white. its rotating. u have to make sum system using sensors etc. so that a computer can tell the direction in which the disc is rotating.
How to implement multiple inheritance when using multiple inheritance programming feature is not allowed? For example, class C inherits from both class A and B.
Asked during second round telephonic interview:
Write a function which detects whether the given number is prime or not. Give the most efficient solution.
Asked during second round telephonic interview:
Given two lists. Write a function to check whether both the lists are equivalent or not.
4. (A) Explain Garbage Collection in .NET framework.
OR
4. (B) How buffer overrun is dangerous, and can be used for hacking.
3. (A) Given two Link List on integers which are sorted, you have to merge those two link lists and create a new LinkList which is also sorted.
3. (B) Give few example link lists to test the above implemented Link Lists.
2. Given an array of integers, {10203004567000}, you have to create a new array which will be like (12345670000000}, without using any other temporary array.
Hi Guys,
I went to the Microsoft written test held in EGL, Bangalore today, and the questions that were asked are as follows:
The pattern of the test was they had given 4 questions and we had to answer within 90 min.
So, the questions are:
1. You are given a TreeNode, and you have to write an algorithm which will return the no. of nodes in the tree.
You have a scooter which needs two tires. You are given three tires. Each tire has a max life of one year. What is the max time you can run your scooter?
hi,
can anyone tel me the difference b/w file pointer and file
descriptor and in
which situation both of them should be used , i need example for both
of them.
A duck, pursued by a fox, escapes to the center of a perfectly circular pond. The fox cannot swim, and the duck cannot take flight from the water (it’s a deficient duck). The fox is four times faster than the duck. Assuming the fox and duck pursue optimum strategies, is it possible for the duck to reach the edge of the pond and fly away without being eaten? If so, how?
A room has 3 light bulbs. There are 3 switches outside the room. You cannot see the lights from outside the room. You can go into the room once. Find out the corresponding switch to each light bulb.
1. What is hash table?
Its access time?
Procedure to insert new element?
2. Given integer array of 199 numbers with 99 numbers repeating twice, find number that did not repeat it self?
Went to ask what if if the array is of Strings instead of number?
3. Program to reverse linked list, where I tumbled.
Given a puzzle of letters/ characters e.g.
a e r o p s
b h a r l s
w r i s l o
a s n k t q
Write a function to which this puzzle and a word will be passed to test whether that word exists in the puzzle or not.
e.g. rain and slow will return true. rain is present in the second column and slow in the third row wrapped around.
A big cube is made of 1000 small cubes. How many small cubes are there at the surface?
What methods are used for collision resolution in hashing? When would you use a tree versus a hashmap?
Print a sorted binary search tree both recursive and non recursive solution.
(inorder traversal)
Just tell me how would you go about reversing a linked list. Told that I would use two pointers, one for the head and one as a temp he was ok with it I guess.
Find out the maximum depth of a binary tree. Hint: its not balanced. I was not able to formulate this solution but was almost there.
Give an efficient algorithm to solve this problem. Given "N" files as input, find the common text fragments that occurs in all the files in input and remove them from the files.
(A fragment is a piece of text that has at least 3 words)
E.g.
Input
=====
File1
------
It is snowing and I want to drive home.
File2.txt
----------
It is snowing and I want to go skiing.
File3.txt
----------
It is hot and I want to go swimming.
Output
=======
Out.File1.txt
---------------
It is snowing drive home.
Out.File2.txt
-----------------
It is snowing go skiing.
Out.File3.txt
----------------
It is hot go swimming.
Given a binary tree,find efficiently if its a binary search tree.
In a class, the new operator is used for allocating memory for objects created . Can this be done using malloc ? If yes, how and if no , why not ? Are there any restrictions associated with the use of malloc in place of new ?
If in a tree , a node can have more than 2 children , is it possible to traverse it in inorder ? If yes , then how would it be done ?
What is the difference between Java and C++?
Why doesn't java has virtual functions?
What is platform independence and how it is achieved?
Find the first non- repeated character in an array
Given a 3 liter jug and a 5 liter jug, explain how you would measure 4 liters.
He was making it more complex by asking to formulate an equation for that .. was just for stress check..
How to debug thousands of lines of software code ?
declaration of "static function" -- what it means ?
What does this code do?
int *p=0;
double *q=0;
printf("%u %u",p,q);
p++;
q++;
printf("%u %u",p,q);
Code for replacing multiple spacing by single spacing in a string...
e.g. " a b c d" --> " a b c d".
Reverse a Binary Tree (not BST)
Interviewer started with giving me a sample of balance binary tree with Depth 3 i.e. so total 7 nodes.
Write a program to generate all the possible magic squares of order N*N where N is odd.A magic square is one in which the sum of all the rows,columns and diagonals is the same
OOP Concept - He wanted me to design a player playing a card game.
My Ans: I explained how a card class can be created with its properties like - Value of a card, Sign of card
Then i explained a class for a player.
He asked - how i will represent a player holding a set of cards.
My Ans: I told that player is a different class and card is a different type of class as explained. And a card's properties can be inherited to a player's class and can be used to represent "a player holding a set of cards.
He explained about a webserver and its logging technique in a log file.. then was asked a question related to regular expression to match a 9 digit number in the log file..
My Ans: [0-9]+ in perl
This site had been useful for my preparation. So, I wanted to post the questions that i faced today in Amazon phone interview. I'm listing the questions..
1) Given two arrays, how will you find out the common elements in both?
My Ans: Take every element from Array1 and iterate it over Array2 to find any match. If matched then print it as a common element. Else go for the second element in Array1 and so on until the end.
2) What is the complexity of the above algorithm?
My Ans: O(m x n) which is equivalent to O(n power 2) if m = n
3) Think of an efficient algorithm for the same problem (He gave me some time and wanted me to mail the code in any language)
My Ans: Create a map with the given Array1. Every element in Array1 will be a key in the map. And the values for the keys contain the number 1 (counter). Iterate Array2 and compare with the keys of map. If present, then increment the corresponding key's value.
Common elements are those that have their key's value > 1. (I assumed that the element occurs only once per array. No repetitions in one array).
4) What is the complexity of the above algorithm?
My Ans: O (n) - because we are iterating only one array
what is difference between declaration and definition in C??
what is free()??
what is realloc()??
difference between struct and class??where to use struct and where to use class??
which executes faster n++ or n+1??
ans:
n++ reason only one operand fetch required...
how wil u determine size of a numeric variable??
soln:(X be a numeric type)
X n=1;
int i=1;
while(n)
{
n<<=1;
i++;
}
return i;
what is difference between pointers in C and C++??
how is sizeof implemented??
design a class car??
how will u find any 5 positive numbers in an array having billion of elements??(efficient solution required)
how will u find 5 smallest primes in an array havin billions of element??(efficient solution required)
wht is memory leakage in C++??
difference between struct and class??
where to use struct and where to use class??
tell me something about MSIT India??
Find the sum of the most common element in a array .
A[]={12,23,24,89,78,76,24}
OutPut:48
In general static variables ?
- Why we use static variables
( He wanted something like, It exists for the whole execution of process. The reason it is not destroyed during function call is , because it is stored in Data segment )
Unix
- IPC (inter process communication)
- how does ls comman work ( Interviewer wanted something like , the command line args are parsed and exec is performed with correspoding executable.
Basic OO Concepts.
- what is OO ?
- Features ?
- Polymorphism
- How it is resolved?
- static methods/ variables in class
- overriding & how is it resolved ? (Virtual methods )
- operator overloading ?
- inheritance ?
Reverse the link list. Write a code and dictate it. Write two approaches: recursive and non-recursive
Write code for strncpy function
Write code for memcpy function
You have an array of numbers from 1-50 in random order. One element is randomly deleted. Write code to find the missing element.
Write code to checking if linked lists merge.
Write code to check if a linked list contains a cycle.
What are the three types of basic variables in Perl?
What would you use to see if a file exists?
find max number of repetitions in an array.like {2,3,4,5,2,3,2} max repeat is 2. optimize it for space then in time.
function to give mask for first 2 non zero (anything except 00) values in int.
find number of 1's in particular number fastest way possible. (use hash table).
basic questions like what is volatile , static and where to use them and why?
write a macro to give offset of particular field in structure.Like struct abc { int a,int b,char c}. Write a macro like offset(abc , c) to find offset of c from top.
reverse binary representation of number.
I have a number in float like 2.5. Store this number in int in such a way that store 2 in bits
31-16 and 5 in 15-0.write a function to do that to convert it and vice versa.
print any tree without using recursion (difficult)
What is "group by"?
Difference between inner join & outer join
Difference between final & finally
What is the significance of virtual destructor?
Discussion on virtual inheritance
Different ways to pass parameters to a function (by value, by reference, by pointer). for the following cases.
6.1 Basic data type (int, char etc)
6.2 Array of integers
6.3 an object of Structure
6.4 an object of a class
Discussed about possiblities of passing constant argument values (by reference, by pointer etc) & their syntax
What is the effect by keeping a constructor private? (in terms of inheritance)
Diference between deep copy & shallow copy
What are local static variables? Its usage & comparison with global static variables & class level static data members
Difference between Malloc vs Realloc
Given a regular expression and a text, find the min no of replacements to be done.
Check if there is a common node in 2 linked lists.
How to find min element in a stack in O(1), where the only operations are Push and Pop.
Write code in any language to check if a string is a palindrome
What happens if you write an integer to disk on one OS and read it on another OS? I said endianess and explained why it matters.
When asked to code fibonacci, I asked iteratively or recursively? He asked what's the trade-off between the two? Then I coded both. He said, there's a bug in your iterative solution. I looked and it and said, int's can be negative. He said, bingo. Then I said, "but I made a precondition that the input is positive." He was like, oh okay and how would you check the condition? I said partitioned equivalence testing for <0,==0,>0.
What VTBL is and why it's useful?
Print a binary tree in zig zag way... that is:
......a.........
....b....c.......
..d...e...f...g..
.h.i.j.k.l.m.n.o.
should be printed as a-c-b-d-e-f-g-o-n-m-l-k-j-i-h
what data structure will u use for that?
Convert a binary tree to a binary search tree... inplace...
Amazon uses a fixed price delivery from city A to city B. How would you save this price info?
Given an array of integers, partition the array into odd one side and even numbers other side.
Given an ancestor matrix for an n-ary tree where a[i][j]=1 if "i" is parent to "j", create the n-ary tree.
Create a balanced binary tree from a given link list
Given a series of alphabetic letters, find the letter occurring second most.
Design a function to find whether a given tree is a mirror of another other tree.
This question was asked at a career fair. There is a string where each and every word is separated by one or more spaces. The string has to be modified in such a way that half of the spaces are put in the first half and the other half of the spaces in the next half with the characters in between. For example, if my initial string is "This is test"(there are totally four spaces), then the output should be
" thisisatest ".
Given an array of positive and negative numbers, find the maximum sum of any subsequence. Return both the sum and the subsequence.
1. Implement memcopy considering the overlap
2. Given a linked list:
a->b->c->d....
Write a function to swap the each node pair , such that output will be as follows:
b->a->d->c->...
Thanx a lot career cup..i got placed into microsoft. it was a campus interview a few days ago. studying the questions on this website helped me a lot and gave me the confidence 2 questions put up in the interview.
it consisted of three rounds
1)technical test consisting of 5 questions for 75 mins.
2)next was a 1hr round in which two questions were to be solved.
3)final round consisted of 2 45min 1 on 1 interviews.
I was only asked DSA an implementation in C an also a few good puzzles.
all the best 2 other aspirants...be confident and prepare well with CAREER CUP.
what do you mean be data structures?
What is a singleton?
Explain : 'ls', 'group', 'pwd' etc...
Design tv remote control for children under age 6
something similar to towers of hanoi.. 10 disks of diff sizes ..5
operations removeblock, putblock, findblock, isempty, isfull given.. no other ops can be assumed. sort the disks in ascending order
Design a social networking site for mobile phones. What are the 5 key features?
You are given a table containing projectname, startdate, end date. You have another table containing projname, developername, testername are given as on mar 24. The project can be in any of the three states: planned, coding in progress, delivered(given to testers). Draw a chart showing the project state per developer as on mar 26
Which routing protocol will you use if you have 50 nodes in each area? Choose between OSPF , RIP and explain.
How will you test if you are given a black box , means you dont know whats inside it or which company is it .. You just know tht it is company covered by black paper.
Why does BGP uses Full-Mesh?
What are the 7 stages through which OSPF converges.
Say you are using a map in your program, how would you count the number of times the program use put() and the get() function? How would you do that if its using multiple maps in the program? How would you do that if the map is sent as a parameter in a method? How would you do it if the multiple maps are passed into the methods (as parameters), and are use differently? (it went on forever....)
What is the difference between Final, Finally, and Finalize?
What does the "Static" keyword do? Do you know any other similar keywords? What are they?
Write code to reverse a single linked list
Given a function
int strcspn(char * source, char * search)
code the most efficient way to return the index of first character that matches in the source string.
eg#
source ="ttbbcca"
search ="ggabba"
the returned value is 6 since the first match "a" occurs at 6th index in source string.
Given a array that contains N integer, find a most efficient way to shuffle the array elements.
What will be the output of the following code for input values (2,2) and (3,3):
int fun(unsigned int m, unsigned int n)
{
if(m==0) return n+1;
if(n==0) return (fun(m-1,n+1));
return (fun(m-1,fun(m,n-1)));
}
Implement float returnAngle(int hour,int min) that tells you the angle between the hour and the minute hands on a clock.
so basically at 2:00 the angle is 60deg, the function should return 60.
Tell me the algorithm for fibonacci series? (When i said there are two - recursive (time effcient) and iterative (otherwise)) Explain the recursive one? What is the time complexity? Why is it O(log n)?
Explain any one routing protocols in detail. eg BGP , OSPF , RIP etc
What do you know about Java generics
What is Little Endian and Big endian ?
What are shared resources?
what is object reflection in Java
How does Java achieve synchronization? Given an class with Synchronized method A and B, a normal method C, there are 2 threads, one instance, can these two threads call A at the same time? call A and B at the same time? A & C at the same time?
Find the two integers in an array whose sum equals to a given value
Tell me about a time where you did something that was difficult from a technical perspective and it solved a problem.
Brain teaser. You have 8 coins, only 1 is more heavy. How to detect it
List as many data structures as you can think of. How do you detect a loop in a linked list?
Write an algorithm to print a binary tree level wise and that too from leaves to root. Also only one queue and one stack can be used for the purpose.
Write a function to add two numbers, without using any arithmetic operator. Even the ++ in for statement is not allowed
If u have to write your own printf and u don't have va_arg how would you get the arguments in the variable list.
Write function similar to malloc.
void* myMalloc(int n)
'n' is the num of bytes to allocate.
You are given a void* f pointer that points to the location free in the memory.
Write the function my2DAlloc.
Minimize the number of calls to malloc.
Also, the memory should be accessible by the notation arr[i][j].
Give you a simplest computer: CPU + 2k RAM. Write a slowest program.
(Hint: use the 2k as a huge number, then use a loop statement to loop from 0 to this number. It will take almost forever.)
Design an algorithm to find the kth number divisible by only 3 or 5 or 7 i.e the only factors of these numbers should be 3,5 and 7.
Difference between int and Integer in Java.
Design for card game where you have a deck, cards, players. This was straight from Career Cup.
I had given a simpler design first with no factory pattern. He extended the problem to have functionality for creating some different kinds of decks also. So I introduced Factory pattern in my design.
Fibonacci Series: write a simple algorithm to find it. He first wanted me to write a recursive one.
What is the running time of this recursive one?
Can you write a better implementation? Its running time? Asked to code it in Java dictate the code.
Where will you use Hashmap as opposed to a Tree? What is the disadvantage of using HashMap?
You are given a lots of files each with billions of lines. You have to extract out ip addresses that occur in them.
(Since interviewer did not ask anything more specific, I suggested doing it using Unix scripting OR use a high level language like Java/C++ OR best use Perl since it is well suited for such tasks.)
What are the interfaces in Collection classes that you worked with?
(Collection, Set, Map, List, Queue)
You have a class that many libraries depend on. You need to modify the class for one application. Which of the following changes require recompiling all libraries before it is safe to build the application?
a. add a constructor
b. add a data member
c. change destructor into virtual
d. add an argument with default value to an existing member function
What would impair your ability to take a decision in a group environment?
Tell me about a time when you had to use your creativity to resolve a problem.
What's your greatest strength?
What kind of leadership experience do you have?
What position (s) are you applying for and why?
If you have other offers what will you look for in the offer to make a decision?
What would your previous managers tell about you?
What is memory leakage? how do you detect it?
Write code to remove spaces from a string in-place
After fork, does new process get file handles and locks?
How do you find dependencies in a large code base?
Find the number of 1's in a 7 bit data using any numbers of half adder. The output format
should be in 3 bits. Eg: 1101001 should give a output of 100.
Let suppose there is a FIFO. Data is written into the FIFO at the speed of 4 ns. A maximum
of 80 words /100 cycle are expected. The read port reads the data at the speed of 5ns. It
can read 80 words/ 80 cycles. What should be the depth of the FIFO so that we dont lose any
data. Hint: Consider the previous cycle as well
Suppose a code in verilog is synthesis by using a tool lets say Xilinx then what would
if-elseif-else would result in?
What is a Branch Target buffer? How is it helpful in reducing bubble cycles in case of
branch misprediction?
What would you do if you were given a 100 million dollars, expecting nothing in return?
Design an alarm for blind? What if the blind person is in the other end of the room?
There is 100mile length tunnel, and two trains whose speed 100mph on the opposite sides. A bee comes b/w two trains with the speed of 100mph.... You guys already know this problem! :)
Write a function which reverses a singly linked list.
Swap two numbers without using a temporarily variable.
Design an algorithm and write code to find the common ancestor of two nodes in a tree
Describe what a singleton is and when you would use it.
What is inheritance and polymorphism? Difference between abstract amd interface?
What is linked list? Write code to detect a loop in a single linked list.
Write a function: you have an array, which consists of some number which are duplicated 2n times, only one number is duplicated 2n+1 times. Your input parameters are the array and the length of the array. Output the number which is duplicated 2n+1 times. I initially told about XOR, but he then told me XOR is not allowed.
You have a stream of lines in a text file. How would you randomly pick one line?
Write a function to reverse a line (i.e "How are you" will become "you are How")
How to delete the kth element from the end of a linked list?
Explain preorder, inorder, postorder and level order of a tree. What is topological sort?
Design an algorithm to find the intersection of 2 sets
Design an algorithm to find the missing number in a set of sequential numbers
Find a median of two sorted integer arrays.
What's the difference between a vector vs array?
What's the difference between a thread vs process?
What's the difference between a mutex and a semaphore?
What's the difference between const pointer and pointer to const.
Virtual functions. How does a compiler know which function to use(virtual funtion table)?
Given an string that has an IP address, write a function to return an integer that has the four parts of the IP address in its bytes.
Implement atoi()
How do you check that a process doesn't access 'unauthorized' parts of the stack?
while(*p++=*s++); // and some discussion on this
Write a function to make a pointer point to a different object.
What is a copy constructor? How do you use it? What's the difference between shallow and deep copy? Why the significance of ambersand (&) in the copy constructor ? What will happen if there is no ambersand?
In unix, how do you kill all child processes of a particular parent?
In unix, what is a defunct process ?
What is the unix command to a kill a process ?
(SQL) What is a foreign key?
(SQL) Explain normalization.
(SQL) What are the different types of joins? Please explain how they differ.
(SQL) Explain cluster index.
If you were to implement a garbage collector in C++ how will you do it?
Why is java secure?
What is garbage collection
What is a pointer?
Remove spaces from a string (in-place)
Detect loop in a singly linked-list
Implement atoi(char *p)
Reverse linked-list
Reverse bit within a 32 bit integer
Implement in-place swap. Now implement one won't cause overflow (i.e: can't use addition)
Draw 2-level paging diagram.
Based upon what points we should choose proper search/sort algorithm for problem solution from all available algos (Quick, heap, selection, shell, insertion, Binary Tree, bubble sort etc.) ? To be specific, when should we use above algos ? examples will be appreciated.
Regards
What are the different features of OO programming? Explain encapsulation, polymorphism, inheritance.
What is multiple inheritance? Is it possible in Java? What is the work around for this in Java? How is it implemented?
If you have a file with each line having 3 values and it represents a range and corresponding value belonging to that range. ie, minimum, maximum, value. Like the following:
20,30,A
41,50,D
31,40,B
51,60,C
Write an algo so that if 43 is given as a key, it must return D as the value. There might be many searches, not just one.
int getValue(int key);
What is happened when a user press a key on the keyboard? (Keyboard generates an interrupt and interrupts the CPU, CPU saves the current process state and executes interrupt handler, CPU returns from interrupt, kernel later on executes device driver to fetch register data from I/O port, ...)
What is in IP header?
What is the diff between hash table and linked list?
What is system call?
What is thread? Compare thread and process. What is the advantage of using thread?
Where is static var stored (in C)?
What is a process? What info need to be recorded by PCB?
Code a function 'dedupe' that removes duplicate characters from a string.
Tell me about a recent bug you tracked down and how you did it.
Whats the difference between statically and dynamically typed languages?
Factorial Factors
The factorial function, n! = 1 · 2 · ... · n, has many interesting properties. In this problem, we want to determine the maximum number of integer terms (excluding 1) that can be used to express n!. For example:
8! = 1 · 2 · 3 · 4 · 5 · 6 · 7 · 8 = 2 · 3 · 2 · 2 · 5 · 3 · 2 · 7 · 2 · 2 · 2 = 27 · 32 · 5 · 7
By inspection, it is clear that the maximum number of terms (excluding 1) that can be multiplied together to produce 8! is 11.
The input for your program consists of a series of test cases on separate lines, ended by end-of-file. Each line contains one number, n, 2 <= n <= 1000000.
For each test case, print the maximum number of factors (excluding 1) that can be multiplied together to produce n!. Put the output from each test case on a separate line, starting in the first column.
Sample Input
2
1000000
1996
5
8
123456
Sample Output
1
3626619
5957
5
11
426566
Given an integer array, design an algorithm to find the three indexes whose sum is equal to a given sum k.
It is a game. There are 1...N persons. the count 'M' is given. The M-th person is out of the game. The recounting starts again from M+1 th person. Finally only one is remaining. He is the winner. Implement the algo.
link list
struct node
{
int d;
struct node *next;
struct node *random;
}
random is a pointer which can point to any link in the link list.One link list is given, you have to create the copy of that link list
Count number of 2's in a given range (0 to n)? (ex: range between 0-20, Ans: 3 (i.e [2], 1[2], [2]0))
Given 2 nodes in a binary tree (not a binary search tree), find the first common parent node. You are not allowed to store any nodes in a data structure.
onsite question:
give you two strings, one source string, one pattern string, check if they are totally match. The pattern string could include '?' which can replace one character. The pattern string could also include '*' which can replace multiple (0-n) characters. For example,
1. src = "abcde", pattern = "ab?de", return true.
2. src = "abcde", pattern = "a*d?", return true.
3. src = "abcde", pattern = "*fg", return false.
I was given about 10 mins, could not work out the '*' case...
Give a very good method to count the number of ones in a "n" (e.g. 32) bit number.(in lg(n) or constant time if possible)
Given an array of size N in which every number is between 1 and N, determine if there are any duplicates in it. You are allowed to destroy the array if you like.
You're given an array containing both positive and negative integers and required to find the sub-array with the largest sum (O(N) a la KBL). Write a routine in C for the above.
Given a Starting Node and Ending Node in a Graph where each Node has a pointer to its parent and all its children nodes. Find all the leaf nodes between the Starting and Ending Node.
Design an algorithm to reverse a string stored in an array.
Had my first and second phone interview with Amazon. I was dropped. This site has been a great help towards my preparation and most questions are based on what you find here.
Posting my Questions is a small way of saying Thanks!
Interview 1:
1. What is polymorphism.
2. Design an OO parking lot. What classes and functions will it have. It should say, full, empty and also be able to find spot for Valet parking. The lot has 3 different types of parking: regular, handicapped and compact.
3. Coding: I have an integer array where every number appears even number of times and only one appears odd times. Find the number.
(I said hashtable and he asked me to write code with Hashtable)
4. What data structure would you use to look up phone numbers for customer names.
(I said Hashtable. Asked why hashtable, why not a tree. I said HT has O(1). Asked is order always 1, when more than O(1) in HT.
Second Interview:
1. Starter: Describe your college projects.
2. OO Design: Design a deck of cards. What classes, data structures will you use? How will you shuffle the cards? How will you divide (deck) among players. What class/function do you need to denote players and where will you add them? What class/function do you need to deck? What if I need to add 2 jokers to the deck of 52 cards.
3. Data Structures: How will you use a hashtable to find data in a tree. (Then he rephrased) suppose I have a hashtable, I want to store the data in a tree instead of a bucket. How will I do it. What complexity to find an element.
4. Bits & Bytes: Find if a binary representation of a number is palindrome. The function should work irrespective of number of bytes for an integer. Suppose if our machine is 4 bytes for an int, how will you use the program for 8 byte machine.
5. Unix: Suppose I have 100's of html files in many directories. I want to find the files having phone numbers.
b) Suppose I have 2 files having phone numbers, find the repeating phone numbers. (I said sort and grep). Then he asked what if the lines cannot be sorted.
All the best guys. I think the second interview was challenging since the interviewer was prodding until he heard a leave me alone. So it means that though they are based on questions in cc, be prepared for extensions. I think this site is all you need to prepare for Amazon interview.
Given a 2D plane, suppose that there are around 6000 points on it. Find a line which passes the most number of points.
Amazon has two log files that have visitor ids not sorted in any order. One is for today and one for yesterday. Find userid common to them. The files have millllllions of entries in both of them and wont fit in memory..either of them.
find the n th largest number in an array (using dynamic prog)
There is a huge file (> 2GB) which has 1 string in every line. What sorting algorithm (not unix/linux commands) will you use to sort the file and why?
If you were to design orkut, how will you design (what datastructure) the network of friends. Also mention how will you find the "mutual friends" etc.,
Given a "directed" graph, write an algo to figure out if the given graph is a tree.
Given an integer n. Create an array of elements between 1..n in random order in the array. The probability of choosing a number for any position in the array should be the same.
You are also given a rand(i,j) function which returns a number between i, j (inclusive) with equal probability.
I had first round of phone interview today. She asked me to write two very simple codes in C++ and dictate her as I write. She was also writing the code as I was coding. The questions were:
1. Write code to find nth node (from front) in a linked list.
2. Write code to find minimum node in a BST.
Then test cases for both of these questions. Then the same question which need use of "uniq" command of UNIX.
Create a Circular Link List from a Given Binary Tree.
give maximum and second maximum of an array
Write the iterative version of post order traversal
What's the most surprising thing you've learned about yourself?
What haven't I asked that I should?
If you were king / queen for a day, what would you change at this company?
Write a function that takes in an array of integers and outputs the number of ways you can combine those integers to obtain a sum of 15.
Example: for [10,5,3,2], output = 2.
what problems do you see in this piece of code (tell without compilation):
template <class Custom = void>
struct Foo : public Custom {
};
template <>
struct Foo<void> {
template <class X>
struct rebind {
typedef Foo<X> Other;
};
};
template <class Base>
struct Derived : public Base::template rebind <Derived<Base> >::Other {
int foo() {
printf("here we are\n");
};
};
main() {
typedef Foo<> Foo_inst;
typedef Derived<Foo_inst> Derived_inst;
Derived_inst ii;
ii.foo();
}
What is the flaw in the design of Java.lang.Stack class of Java
What are memory static variables are created?
what is the difference between template in C++ and generics in java
Print all elements of binary tree with each level on different line
there is an array of numbers.
find out whether two numbers a and b exist in this array such that a+b=20
Reverse a linked List using recursion,by using one argument only
What is the use of volatile variable.
Explain it in Singleton class also for lazy initialization.
How Java is plateform independent
If you have been given opportunity to change some of Java feature, Which feature would you like to change
A pile of nuts is in an oasis, across a desert from a town. The pile
contains 'N' kg of nuts, and the town is 'D' kilometers away from the
pile.
The goal of this problem is to write a program that will compute 'X',
the maximum amount of nuts that can be transported to the town.
The nuts are transported by a horse drawn cart that is initially next
to the pile of nuts. The cart can carry at most 'C' kilograms of nuts
at any one time. The horse uses the nuts that it is carrying as fuel.
It consumes 'F' kilograms of nuts per kilometer travelled regardless
of how much weight it is carrying in the cart. The horse can load and
unload the cart without using up any nuts.
Your program should have a function that takes as input 4 real numbers
D,N,F,C and returns one real number: 'X'
Do not worry about drinking water, or other "real world" issues.
write a program that accepts two mandatory arguments without using any built in date or time functions . The first argument is a string "[HH:MM {AM|PM}" and the second argument is an integer which denotes minutes. The minutes get added to the string. The return value or output of the program should be a string of the same format as the first argument. For example AddMinutes("10:23 AM", 13) would return "10:36 AM
write a program that accepts two mandatory arguments without using any built in date or time functions . The first argument is a string "[HH:MM {AM|PM}" and the second argument is an integer which denotes minutes. The minutes get added to the string. The return value or output of the program should be a string of the same format as the first argument. For example AddMinutes("10:23 AM", 13) would return "10:36 AM
Given an infinite sequence of bits. In that, one region of the sequence is continuous 1's and other region is continuous 0's. Assuming that LSB (Least significant bit) is 0 (point where to start), find the position of the bit sequence where first 1 appears if you start from that LSB end.
Now suppose you have 3 eggs and N stories building. If an egg drops from k-th floor or about it will break. As before you need to minimize the number of egg drops to find k in the worst case
8 tires were used on a bus (6 tires) which has traveled 16000 km. How many km did each tire sustain, if all the tires were used equally in sustaining this distance?
Given an int array of size billions.Print the 100 max elements from the array in O(n).You are allowed to modify the array if u want to.
S = {Si, i=i,I} Set S has I elements
P = {Pj, j=1,J} Set P has J elements
Q = {Qk, k=1,K}, Set Q has K elements
Define a unique mapping F = {Si, Pj} ? {Qk} for some i, j, k.
Find the following mapping pairs {Si, Pj} ? {Qj} where i’s are unknown and j= m1, m2 where m1 and m2 are given.
Is it possible to find a polynomial time subset R of S (say i=r1,r2 where r2-r1 = r, i.e. of size r) that is guaranteed to include all of above Si’s.
Explain Hash Table from the scratch as if I don't know anything.
Given a sorted array with repeated nos e.g
1,2,2,7,7,7,7,9,9...
Find first occurence of any given value.
How to implement your own HashMap in java
give the algorithm for checking anagram
Why should you not make your Sinleton claas as Serializable and Clonable.
What is the difference between sleep and yield method
What is the limitation of singleton pattern
How to make a class as final in C++.Means no one should be able to extend that class.
Tell the situation where we can use nested classes.
What was the problem in implementing double checked locking before java 1.5.
Why Java language designer has chosen to make all the variable inside an Interface as public ,static and final.
What is wrong with the below method?
public int getchar(string s)
{
string s1=s[3];
}
How do you programitcally create & terminate a process on linux
I am trying to write a program to find the longest word made of other
words. For instance, If my file has the following words (sorted):
test
tester
testertest
testing
testingtester
The longest word should be testingtester. I am trying to use "Trie"
for this. But, I guess there might be some problem in using this. Can
you suggest me any other better solution for this?
Thanks in advance
Given an array of integers, write a function that returns the difference between the largest even integer and the smallest odd integer.
Sample input: [17 6 13 31 2 8 23]
Correct sample output: –5 (= 8 – 13)
Given a matrix (2D array) of m x n elements (m rows, n columns), write a function that prints the elements in the array in a spiral manner.
Sample input matrix:
1 2 3 4 5 6
7 8 9 10 11 12
13 14 15 16 17 18
19 20 21 22 23 24
25 26 27 28 29 30
Correct output for above sample input:
1 2 3 4 5 6 12 18 24 30 29 28 27 26 25 19 13 7 8 9 10 11 17 23 22 21 20 14 15 16
Design a web crawler .. how will you avoid from getting into infinite loops ..
Explain Queuing models.
- When to use Refernece/Pointer
- What is Copy ctor? Passing by ref to const
- Mutable? Why use it?
- Design a web browser class.
- Why use Exceptions? What are some of the concerns with exceptions?
- What is a dynamic cast? And when do we use it?
- What is a design patter? Name a few design patterns.
- What happens when you take the address of a reference?
- Few behavioral questions.
This was a phone screening. Will report more with the onsite questions.
Transform (rotate 1 step clockwise) 2D array as follows.
Do rotations for each layer.
1 2 3
4 5 6
7 8 9
Into
4 1 2
7 5 3
8 9 6
if there is a huge file in which all lines are unique except two.what is the best way to find line numbers of these 2 duplicates
Telephonic Interview 3)
1) Generate 1st ten prime numbers.
[ Note - Interviewer needed a simple but smart approach instead of high-fi prime number generation algorithms. The "simple" approach should not be brute force]
2) Given 2N + 1 number out of which 2N numbers are duplicate find the unique number.
3) Given a sequence of number Generate cross product of all numbers such that the product at any index does not use the number at the same index.
Example
arr = {a1, a2, a3, a4, a5 };
product[] = {a2*a3*a4*a5, // a1 not used
a1*a3*a4*a5, // a2 not used
a1*a2*a4*a5, // a3 not used
a1*a2*a3*a5, // a4 not used
a1*a2*a3*a4 // a5 not used
}
Telephonic Interview 2)
1) Design a Hotel reservation system which will support the following functions.
a) User will get a list of all different types of rooms.
b) User selects a room type & check the room availabilty between the specified dates.
c) User Makes Reservation.
[Discussed about "locking" the room availbilty or not in case if user wants to proceed with reservation]
Telephonic interview 1)
1) 2) Given a log file with user information select one Random winner from the users. You can use constant memory
2) Given 2 arrays of integers find the common elements of both arrays.
[Discussed different approach using Hashmap, Binary Search Trees, Sorting etc]
3) Discussed different approach to find unique element from a set of 2N numbers where only 1 number is unique
[Discussed different approach XOR, Sorting etc. Asked me to write sorting based approach & send him]
Onsite interview 1)
1) Represent a Tic Tac Toe game class.
2) Now write a function IsWinner which takes a player as input and returns whether the player has won or not.
3) Now write a funtion Play which plays the game
Write code to reverse a singly linked list
Implement a function which returns the 2 largest numbers in an array.
What is DMA? Can user level buffer / pointer used by kernel or drivers?
What are the various ways in singleton pattern can be made to fail and how to avoid them ?
Function which lists all the possible dates for given year.
Write a function to find intersection of two arrays.
The program would take as input the amount the customer
gives and outputs how many 1 cent coins, 5 cent coins, 10 cent coins , 25 cent coins and $1 bill you need to give out.
2.88 cents
void printChange(float amountToReturn)
{
int atr = amountToReturn;
cout<<"Nos of $1 Bills : "<<atr;
amountToReturn -= ((float) atr);
atr = (amountToReturn * 100.0);
cout<<"25 Cents : "<<(atr / 25);
atr %= 25;
cout<<"10 Cents : "<<(atr / 10);
atr %= 10;
cout<<"5 Cents : "<<(atr / 5);
atr %= 5;
cout<<"1 Cents : "<<atr;
}
//Each day $10
//75 miles free per day. $0.25 per extra mile
//ChildSeat : max 2. Each $25
float CarRentAmount(int days, int miles, int childSeat)
{
float amt = 0.0;
if(days <= 0)
{
cout<<"Invalid nos of days\n";
return amt;
}
if(miles <= 0)
{
cout<<"Invalid nos of miles\n";
return amt;
}
if(childSeat < 0 || childSeat > 2)
{
cout<<"Invalid nos of children seat\n";
return amt;
}
amt = ((float) days) * 10.0;
float allowedMiles = 75.0 * ((float) days);
if(((float) miles) > allowedMiles)
amt += (((float) miles) - allowedMiles) * 0.25;
amt += ((float) childSeat) * 25.0;
cout<<"Total amount to Pay : "<<amt;
return amt;
}
-----------------------------------------------------------------------------------------------------------------
//check password, only 'm' mistakes accepted
//return 1 : code accepted
//else code not accepted
int verifyCode(char input[], char orig[], int m)
{
int miss = 0;
int len = strlen(orig);
if(strlen(input) != len)
{
cout<<"Invalid code\n";
return 0;
}
if(m < 0)
{
cout<<"Invalid mistake allowance\n";
return 0;
}
for(int i = 0;i < len;i++)
{
char origchar = orig[i];
char inpchar = input[i];
if(origchar != inpchar)
{
switch(origchar)
{
char '1' : if(inpchar != '2' && inpchar != '4') return 0;
miss++;
break;
char '2' : if(inpchar !
1st phone interview
How would you implement Hashtable.
Explain Observer pattern
Suppose you have N books. Each book may have soft copy, hard copy, CD, DVD format.
Design the data structure to hold the N books & its different formats in memory. This data structure should support the functionality that [any] 1 format of the book, will be displayed as its primary format in GUI & the remaining formats should be displayed as secondary format.
If the popularity of some format for a particular book is more than other formats how will organize/choose the data structure.
Algorithm & design for Tic-tac-toe game. Function which takes the player as input & return whether the player has won the game or not.
Lets say A is a friend of B and B is a friend of C then A and C are two degree friends. So we have to implement a function that takes two friends and return true if they are 2 degree friends. How will you implement this function efficiently.
What is stack. How do you implement it. Now lets say we want to add a new function called min which return the min element on the stack along with push and pop. Like push and pop this min function should also be a constant time operation how will u do it.
Background:
For any perimeter of a rectangle, there may be multiple different dimensions that result in that specific
perimeter. When there are multiple dimensions for the same perimeter, there may also be multiple areas. In other words, any one perimeter can result in different areas depending on the possible combinations of dimensions that can make that perimeter.
Definition:
A dimension or instance of dimensions for a rectangle is a pair of length and width values. A dimension with length 5 and width 4 is considered the same as a dimension with length 4 and width 5. The area of a rectangle is the length multiplied by the width. The perimeter of a rectangle is equal to the sum of the lengths of all 4 sides or the sum of 2 multiplied by the width and 2 multiplied by the length.
Requirement:
A finite set of possible perimeters of a rectangle exist given a maximum perimeter, minimum length of any side, and the constraint that all sides are whole numbers; we will call this set U. Find the subset of perimeters in set U where all of the possible dimensions for a perimeter in the subset have areas common with the areas of one or more other perimeters in set U. Your program should take the minimum length of any side and the maximum perimeter, respectively, as command line arguments and output a comma separated list of the perimeters that meet the criteria explained above, sorted from lowest to highest. The program should be submitted in a single Java class with an implemented main function that provides the correct output given the two input arguments.
Example:
javac YourClass.java
java YourClass 1 64
10,14,18,20,22,26,30,34
Please make sure your program can be run with the exact syntax above. You can name the class anything you like, but the class name will be passed to a program that will compile it and then run a set of tests on the resulting program. It is important that your class will compile and run from within a local directory, not a package directory.
A circus is designing an act consisting of a tower of people standing atop one another’s shoulders. For practical and aesthetic reasons, each person must be both shorter and lighter than the person below her. Given the heights and weights of each person in the circus, what is the largest possible number of people in such a tower?
Input(ht wt) : (65, 100) (70, 150) (56, 90) (75, 190) (60, 95) (68, 110)
Output: The longest tower is length 6 and includes from top to bottom: (56,90) (60,95) (65,100) (68,110) (70,150) (75,190)
A 2D array is such that each row in it is in ascending order and each column is in ascending order. How will you search for an element in this array?
A city is represented as a grid where each line represents a road. As it is a grid, all the horizontal roads intersect with all vertical roads. A bus may enter the city in the left-bottom junction with a North seeing face (direction of the bus). You can move to any of the intersections with a proper control string. Eg "LLMMR" L, R, M representes that the bus has to be turned to its left, right and then has to move one step forward and reach the next intersection. How will you design this scenario? What classes are needed? What member variables and functions are needed?
A tree is represented in a matrix form such that A[i,j] = 1 if j is the ancestor of i. Otherwise A[i,j] = 0. Given this construct a normal binary search tree.
There are n petrol bunks arranged in circle. Each bunk is separated from the rest by a certain distance. You choose some mode of travel which needs 1litre of petrol to cover 1km distance. You can't infinitely draw any amount of petrol from each bunk as each bunk has some limited petrol only. But you know that the sum of litres of petrol in all the bunks is equal to the distance to be covered.
ie let P1, P2, ... Pn be n bunks arranged circularly. d1 is distance between p1 and p2, d2 is distance between p2 and p3. dn is distance between pn and p1.Now find out the bunk from where the travel can be started such that your mode of travel never runs out of fuel.
Find anagrams from a dictionary. eg stop, pots are anagrams
Phone Interview:
The guy who interviewed me is a project leader at Bloomberg. He was very arrogant and
his english was very poor.
First he asked me to explain what I have worked on at current company. So I explained him the distributed system I built at world's 3rd best research organization. The discussion went on for 30 minutes and at the end He laughed at it and claimed that its not a real distributed system!
He then asked following C++ questions:
1. Can you have private destructor and private constructor ? explain your answer.
2. Can you have virtual constructor ? explain your answer.
3. What design pattern is similar to virtual constructor ?
4. Can you have vector of auto_pointer ? explain your answer.
5. is this code valid:
auto_pointer<Object> a(new Object());
auto_pointer<Object> b(new Object());
a = b;
My Answer: Yes its valid ( I checked in the book later)
but he insisted that this is invalid code! what an idiot.
If he comes on the phone to interview you, just say "No Thanks!"
Write code to reverse a linked list.
how do you implement hashmap, get(key), set(key,value) methods?
can somebody tell what could be the best approach?
Write an aligned malloc & free function. Which takes number of bytes and aligned byte (which is always power of 2)
Ex. align_malloc (1000,128);
it will return memory address multiple of 128 of the size 1000.
aligned_free();
it will free memory allocated by align_malloc.
Write an printhex function which implements "%x" in printf without using printf.
Example :-
printhex(10) output is A .
A class that many libraries depend on. Now you need to modify the class for one application. When do you need to recompile other libraries.add a constructor? add a data member?change destructor into virtual? add an argument with default value to an existing member function? C++ question.
What data structure would you use to implement MS Excel? Justify your approach.
Some sort of a planning problem
5 friends 5 cities 5 distances ...
some 6 conditional statements given
map the friends to cities and also map distance to cities such that
the conditional statements are true
Find the median value of two sorted arrays.
Asked in 1st and 2nd interview at campus placement at IIIT Gwalior.
An 8 x 8 char array is provided with random letters. You have to tell if a given string occurs.
eg
String to find = "computer"
Array[] = {
b b b b b b b b
b b b c b b b b
b b o b b b b b
b b b m p b t b
b b b u b u b e
b b b t b b b r
b b b e b b b b
b b b r b b b b
}
Ans : Available
Explain how congestion control works in the TCP protocol.
Implement division (without using the divide operator, obviously).
Describe an alogrithm to find out if an integer is a square
You need to check that your friend, Bob, has your correct phone number, but you cannot ask him directly. You must write a the question on a card which and give it to Eve who will take the card to Bob and return the answer to you. What must you write on the card, besides the question, to ensure Bob can encode the message so that Eve cannot read your phone number?
How do you find, if a machine is big endian or little endian?
Order the functions in order of their asymptotic performance
1) 2^n
2) n^100
3) n!
4) n^n
How long it would take to sort 1 billion numbers? make any assumptions you wanted.. assume the computer would have more than 4 GB of RAM, so the array would fit in memory in its entirety, and the machine would run at 4 GHz.
There are 10 PC in a network. 9 PC work fine and can open any internet website including google.com
but 10th pc in network had a small exception. You can surf any website on that pc but when you try to open google.com its shows page not found error.
Whats is the problem on that 10th pc and how you will resolve it ?
What is TCP, UDP. what is reliability, unreliability, give examples of these?
What is indexing, what is the input and output to it.
Given n non overlapping intervals and an element. Find the interval into which this element falls.
What's the difference between mergesort and quicksort? When would you use each?
Write a function to find mid point of a linked list
Given a N*N chess board, a robot starts from the left-up corner and ends at right-down corner. It can only move one cell per time and the direction must be right or down.
Give the algorithm that count all possible paths.
1.) What is difference between IPv4/IPv6 protocol
2.)OSI & TCP/IP stack layers + protocols at each layer.
3.)What is network/subnet mask. Explain how a host A sends a message/packet to host B
3a.) When both are on same network
3b.) When both are on different networks
You need to explain which layer takes routing decision and how.
4.) What is TCP/UDP. Difference between both. And explain how TCP handles reliable delievery(explain ACK mechanism), flow control(explain TCP sender's/receiver's window) and congestion control.
How would you test the efficiency of a traffic light.
Propose a tree based data structure to identify a node with nth rank with maximum efficiency .
Explain and write the code for Concurrent Read, Exclusive Writer
Implement Run Length Encoding.
Given a binary tree link all the right child of a node to their left siblings if present.
Consider the following IDL interface:
interface Time_Server
{
// Return the time on the server
string get_timestamp();
};
Write a client that for each command line argument(1) queries the naming service to resolve an object with the name provided on the command-line, (2)uses the object obtained via the naming service to query the time and (3) repeats the process after 60 seconds. Your code should not leak resources, continue to work despite exceptions, print all successful results to standard output & report all errors to standard error.
[There is some supporting code from Automated Trader's desk under the same directory]
Consider a TCP/IP server that passively waits for client connections. Once a client connects the server reads data from the client one character at a time. If the server receives character 'Q' it sends it back to the client the number of client currently connected(as a string). If the character is 'T', the server should send back the local timee, as a string in HHMMSS format. Characters '\r' and '\n' are ignored, all other characters result in the server returning the string BADREQUEST. The server is, or should be, able to handle multiple concurrent clients
Given n cities with their populations, suggest an algorithm to pick up one of the cities randomly such that more the population of city is more chance it stands to be picked. Assume you can use an inbuilt random generator function from the language library.
Implement Strtok function.
Onsite Interview (coding test) --
Q4) Implement a Singleton pattern as a template such that, for any given class Foo, I can call Singleton<Foo>::instance() & get a pointer to a singleton of type Foo. Assume the existence of a class Lock which has acquire() & release() methods. The implementation should be thread safe & exception safe
Onsite Interview (coding test) --
Q3) Now write a derived class Undo_Buffer that derives from Buffer. It will provide the ability to undo the last change to the buffer. It should have a member variable, last_buffer, which is a copy of the internal unsigned char array from the last change to the buffer. For example, if the buffer has "0123456" and undo_buffer[3] = 'z' is called, then the Undo_Buffer class holds the new change value of "012z456".
Undo_Buffer should provide a method undo() which will revert the buffer to the last saved buffer. There does not need to be any access to the last_buffer, except to provide the functionality of undo.
Onsite Interview --
Directions
1) Write compiling (& working) code on linux
2) 2 hours.
3) Total questions 6 Mandatory 4(but 3 oky)
Q2) Write a simple buffer class that provides a fixed length of unsigned char. While you should not use the STL to implement the class the class should be written in such a way that it can be used in an STL collection (i.e std::list<Buffer> should work). Instances of Buffer should be allowed to be instantiated with an initial buffer size. Provide a reqize(size_t) method that will shrink or grow the buffer. Provide access to individual elements of the buffer (i.e the ability to get/set the nth element of the buffer)
Onsite Interview --
Directions
1) Write compiling (& working) code on linux
2) 2 hours.
3) Total questions 6. Mandatory 4 (but 3 acceptable)
Q1) Write a recursive funciton "sum" that computes the sum of all integers between 0 & n. For example, presented the number 10, it would return -15. Next, write a "main" that will drive the function by calling it for each "valid" argument in the program's argument list. If an argument is not an integer then print out an error message, wiht the double quotation marks.For example calling the program with
a.out 23 -12 foo 7
should result in output like
Sum of all integers between 0 & 23 is 276
Sum of all integers between 0 & -12 is -78
"foo" is not a number
Sum of all integers between 0 & 7 is 28
You have two identical roop. Both of them have the following properties:
1. Each burns in one hour.
2. They burn at a non-uniform rate. i.e. there is no correlation between the length of the rope with the time it takes to burn it.
Using only these roops find out when 1.5 hrs have elapsed?
Intervier: Take any word, remove vowels and place them in reverse order by untouching consonants and place them back. Word is AIRPLANE.
Implement strstr
Reversing a linked list
Can u have a floating point operation inside a interrupt handler?
He asked me this question after he asked me whether there can be a print message inside a interrupt handler.
1. DMA controller.
2. Cache coherency.- MESI /MSI protocol
3. Cache coherency mechanism.
4. Interrupt handler.
5. what happens when function1 calls function2 with it.(like where does the linkage register stuff get stored..and resume execution)
6.Can u have reentrant code inside interrupt handler. (NO)
7.What will happen/can u have printf/printk inside an interrrupt hancler (i think he wanted me to say no.. but I did not know the reason)
8.context switch.. when do u need it.
9.what does a interrupt handler take in as input... and what does it return.( it does not accept or return anything)
10. what is the difference between ISR and interrupt handler.(Both are the same)
11.how to search a book in one million books.
12.How to check whether a linked list is circular.
1. which kernel were u working? debugging techniques? challenges?
2. a mad user tries to allocate 1 gb memory using calloc.
but the program fails after allocationg about 800mg(appx. i dont remember). Tell me what could have gone wrong?
3.
We know disabling interrupts works only if it is single processor(i.e local disabling of interrupts).
Consider this case where we have a SMP(symmetric multi proc) the processor. Processor-1 wants to perform some critical operation so it disables all the interrupts.
What will happen when processor-2 throws an interrupt.
pretty easy question.
print out all positive integers from 1 to 100, inclusive and in order and state whether each integer is odd, even, divisible by both 2 and 3, or divisible by 3. design logic to be as efficient as possible.
example output:
the number 1 is odd.
the number 2 is even.
the number 3 is divisible by 3.
...
the number 6 is divisible by 2 and 3.
Given an API Method
int max(int x, int y)
{
//code that returns the max value
}
Need to test the above method at API level. So tell me the test cases that you come up with?
When would you use BST over a hash, assuming perfect hashing
You are given a list of objects and each object has a weight. Write a function to randomly return one of the objects. There is one constrain, the probability an object is picked is proportional to its weight over sum of all weights, for example, an object with weight 2 should be picked 2 times as frequent as object with weight 1 is picked.
Given a list of integers {5, 5, 10, 5}. Output the list of integers that will sum up to 15.
e.g. {5, 10}, {5, 10}, {10, 5}, {5, 5, 5,}
Generalize the algorithm to work on any input size.
To find 2 numbers in an array that sum up to a target number 'x'
Given a source word, a target word, and a dictionary, how to transform the source word into target word by changing only one letter in each step. The word you get in each step must be in the dictionary.
What's the difference between process and thread? What kind of information does thread maintain? its own stack? heap?
How and when to do a context switch? How do you handle an time slice interrupt?
What are the possible pitfalls for multi-thread programming?
Simulate a seven-sided die using only five-sided
How to partition text into words, where there are no space characters in the stream of
This one is interesting:
How to store passwords in database? How to use them? How to store SSN in database? Is there difference? Hint: Do you really want to see the actual password when they are retrieved? Do you want to see SSN when they are retrieved?
Implement the stack in such a way that push,pop and minimum find in the stack operations are o(1).
What is the constant time algorithm to extend the capacity of a Vector when its current limit is reached.
There is an 100 storied building and you are given 2 glass balls. Find the floor where the ball will be broken when you throw it. Find it in minimum number of throws.
What is the minimum number throws???
A single linked list whose nodes are defined as follows:
struct node
{
node* next;
note* reference;
char val;
}
Implement node* duplicate(node* list) that duplicate the input list in O(n) time and O(1) space.
"hELLo wOrLd1"
Reverse the characters, upper to lower,
lower to upper, etc...
Write code for extracting unique elements from a sorted list of array
Create an efficient (time and memory wise) for the following:
You have a dictionary of names of phone numbers. As a user is searching for a name it should show all possible combinations.
For example. As user types 'D' it should show all names beginning with D. And then when user types 'a', it should show all names beginning 'Da' etc. Something like Google sense does. So at each point of time show end users the possible combinations.
Part II. The string could be random in nature and user need not begin at the start. For example, in the name Daniel, the user can give string 'nie' and the algorithm should should show all names in the dictionary with substring 'nie' which of course will include 'Daniel' and many others. You have to design a memory and time inexpensive operation.
Given a Task List of the form:
typedef struct task* task_ptr;
struct Task {
int Priority;
int *Dependency;
task_ptr next;
}
No of tasks range from 1 to N. (N know at run time)
Priority ranges from 1 to N
Dependency ranges from 0 to N. 0 means it doesnt have dependency on any other tasks. Each task can have dependency on more than 1 task.
So if task 2 has Dependency array as {1,3,5} it means it can be dequeued only after 1,3,5 are removed
You were to write two functions
1) void enqueue( task* head_list, task *T);
Which enqueues a task in the list
2) struct task* dequeue(task* head_list);
Which dequeues the task with highest priority 1st, given it has no dependency or all the dependent tasks have already been dequeued.!
Write the function in C/C++ for optimal insertion and deletion .You are allowed to use any data structure you want.
How to identify bits that alternate 1 and 0. Ex: 101010, 10101, 01010, 01
There are 1 million html files. Find "www.amazon.com" in these files.
Given an array of numbers that repeat even number of times in the array except for one number occurring odd number of times. Find the number repeating odd number of times. Ex: {1, 1, 3, 3, 3, 7, 7, 7, 7} and 3 is the number.
Given a string with multiple occurrences of characters (e.g. abaabcddeadegfhhh) return a string that contains characters that appear an odd number of times. (In this case it would be (dgfh)).
There are 25 horses and 5 lanes. You have no idea about which horse is better than other.
Find in minimum possible races, the first three fastest running horses.
We can find out whether a singly linked list has a loop in it using 2 pointers(another common interview question). How can we find the start of the loop?
For e.g. given 1-->2-->3-->4-->5
| |
8<--7<--6
How will u find out that '3' is the start of the loop?
Do you know the big difference b/w .NET and JVM? (I answered CLR, and it's correct) What is .NET? (A sort of JVM with gc :)
Write a code segment called isFibonacci(), which, when given a variable array of integers, checks whether it is a part of the Fibonacci sequence or not? (This was asked for the second round)
Design an in-memory file system, with code.
struct Object {
// THESE FIELDS ARE ALREADY DEFINED; YOU MAY NOT MODIFY THEM
Object* next_ptr; // Next object in list; NULL if end of
list.
unsigned int ID; // unique identifier for this object.
unsigned int parent_ID; // 0, if object is root of tree.
// THESE FIELDS REPRESENT THE TREE WHICH NEED TO BE FILLED
Object* parent_ptr; // Initialized as NULL.
unsigned int child_count; // Initialized as 0.
Object** child_ptr_array; // Initialized as NULL.
} ;
Need to implement the method:
Object* convert_List_To_Tree (Object* list_head);
This returns the pointer to the root node
How would you increase the capacity of a server which is hosting a site, for ex: CNN, it has a huge no. of requests. How would you make the site to support that much traffic?
1. From which memory do static variables get allocated?? - Global memory i guess
2. Indirectly asking about virtual destructor?
3. If u have 1K as ur heap memory can a call to malloc(1 K) succeed??
4. what is the difference between static variable and local variable?
5. Hash a string of length 100 ? he was asking me a hash function?
Write a Java program to check whether any two elements in an array add to a constant C or not. Implement the program with least complexity O(n).
How would you test a BLENDER?
Asked me to test the notepad's find dialogue box.
Given a list A with n elements, produce a list B with n elements such that the ith element of B is equal to the product of all elements except the ith in list A. Example: Given list A = [1, 2, 3], make a function f(x) such that f(A) = [6, 3, 2].
There are three people who want to know the average of their salary. How can they get the average without disclosing their salary to each other?
Write a program to add two numbers a and b.
1. Without Using + operator
2. Without using any loops
Write code to verify if an IP address taken as an input string is valid or not.
Given two events with integer start and end times, E1 = (s1, e1), E2 = (s2, e2), implement a quick boolean check to see if the events overlap.
You are given a Linked List and a function declaration as node* KReverse(node* head, int k);
KReverse is a function that reverses the nodes of a Linked List k at a time and then returns the modified Linked List.
For Example
Linked List : 1->2->3->4->5->6->7->8->9->10->11
For k = 2
Return Value: 2->1->4->3->6->5->8->7->10->9->11
For k = 3
Return value: 3->2->1->6->5->4->9->8->7->10->11
Write a solid secure definition for the function KReverse.
1) Design a synchronous circuit which follows this pattern:
1000
1100
1110
1111
0111
0011
0001
0000
1000
Is it possible to design this circuit if there is no reset. If yes then how?
2) Design a circuit which generates the following pattern:
1000
0100
0010
0001
0010
0100
1000
3) In the above mentioned question how many FF's are least required? Justify your answer!
4)Generate the above mentioned pattern by using only combinational logic and D FF.
Should pointers be always initialized?
Which OS do you use, and why?
What would you say is your weakness?
How do compilers work?
Explain Hashtable
Does anybody have any experience with superday interview with Goldman Sachs? I am going there for a superday for a analyst/programmer position in one of their secDB tech teams. The position requires 2-5 years experience.
Thanks for sharing!
Count the number of bits that are 1 in a byte. (Char passed to function)
Given a string "abc&xyz<def mno>" and its processed string
"abc&xyz<def mno>"
now & is mapped to '&'
<-> '<'
>-> '>'
write a function to convert into original form
for above example original form would be
"abc&xyz<def mno>"
void groupThatEquals( int total, int groupSize, int[] numbers )
This is a prototype of the function where number is given an array of ints, total is given as a number and groupsize is also given as parameter.
For example, an array of numbers is 3,4,16,2,13,8,5,7,2,9
Suppose Total= 28, groupSize = 3
So we have to come up with a group size of 3 in this example whose sum will be equal to 28. In this case it is 3,16 and 9 which makes total = 28. Array is not sorted and number need not be contiguous.
We have to find all possible groups that sum to Total.
There are thousands of webpages. Find all the files where the hyperlink "www.amazon.com" occurs and append a string to it. For example, all "www.amazon.com" hyperlinks become "www.amazon.com?id=123"
you have a [n * n] array which is sorted both row wise and column wise. How do you find an element in this array in O(n) time ?
Microsoft onsite multithread synchronization interview question
1. Suppose we have a class:
class Foo {
Public:
A(.....); //if A is called, a new thread will be created and the corresponding function will be executed.
B(.....); //if B is called, a new thread will be created and the corresponding function will be executed.
C(.....); //if C is called, a new thread will be created and the corresponding function will be executed.
......
}
Suppose we have the following code to use class Foo (We do not know how the threads will be scheduled in the OS.)
Foo f;
f.A(.....);
f.B(.....);
f.C(.....);
Questions (Part A):
1. Can you explain multithread synchronization mechanism?
2. Can you design a mechanism to make sure that B is executed after A, and C is executed after B?
Questions (Part B):
Suppose we have the following code to use class Foo (We do not know how the threads will be scheduled in the OS.)
Foo f;
f.A(.....);
f.B(.....);
f.C(.....);
f.A(.....);
f.B(.....);
f.C(.....);
Q: 1. Can you design a mechanism to make sure that all the methods will be executed in sequence?
Questions (Part C):
2. Can you design a mechanism to make sure that all the methods will be executed in sequence, in this case the caller should
be nonblocked?
3. Can you design a mechanism to make sure that all the methods will be executed in sequence, in this case the caller and the
called methods should be nonblocked? (hint: use call back).
Please write the corresponding code.
Write code to print the Fibonacci series.
You have a cube that is painted red on all 6 sides. If you were to make two symmetrical cuts in each dimension, you would have a total of 27 pieces. How many pieces have red on all 4 sides, on 3 sides, on 2 sides, on 1 side and on no sides?
Heres the best way I can explain the cut in one dimension:
=============
| 1 2 |
| 1 2 |
| 1 2 |
| 1 2 |
=============
where the vertical '1' and '2' lines are the cuts so now you have three pieces. So imagine that in every dimension.
An array of size n, has n/2 unique elements and n/2 occurences of an element. Find the non-unique element in linear time?
How would you find out occurrence of "world1" in a previous or next line to in which "world2" occurred using grep?
I: Interviewer M: Myself
I: Amazon.com will log all the customers who will visit the website with date and customerID. each day we will create a separate log files.
I want to find the customers who visited on yesterday but not on today.
EX: I have two log files i.e. Feb1.log Feb2.log . I want to find the customers who visited on Feb1st not on Feb2nd. Note: There will be millions of entries in each log file
I: Interviewer M: Myself
I: What is singleton pattern?
M: Explained about singleton pattern and constructor to be private and there will be a method (Static) which will return the object.
I: How can i achieve Thread safe in this implementation?
M: In Java we need to use "synchronized" keyword in order to make that method thread safe.
I: If there are Million threads accessing this method, as you used synchronized all the other threads has to wait, which makes the application to run slower. So how can you achieve thread safe with out using synchronization?
What is a database
You are given inorder and preorder traversal of a binary tree in file. Can you create the binary tree ?
Write code in C using the following prototype.
btreenode* CreateBinaryTree(char *preorder, char *inorder, int len), where len is the length of the inorder/preorder string.
1. Given a huge file containing integers, how would display the 10 largest numbers in the file. There is a memory constraint and hence we cannot pull the whole file into any extra storage/Data structure.
2. Display all the numbers in the ascneding order without pulling the whole file into any extra storage/data structure.(managing memory efficiently)
What is a Build Plan?
In my 1st Phone interview:
What is Linked List?
Interface and abstract class
Write java code for prime no:
Threads
Garbage collector
Vector and Arraylist
HashMap and HashTable
Externalizable interface
Inhouse interview question:
You have an array of char's like so:
[12, 46, 244, 0, 12, 83, 48, 98, 233, 83, 26, 91, 119, 148, 98]
Whats the best way to return the first repeated element. The first one in this case is 12.
If you have a linked list of length N, whats the best way to find element that is X from the end (X is assumed to be less than N)
If a node is down on a network, what steps would you take to debug it?
Get all Rational Numbers such that:
1. Both numerator and denominator are strictly 2 digit numbers.
2. The last digit of the numerator = first digit of denominator
3. If you remove the last digit of numerator and first digit of denominator you will end up with the same numeric value
For e.g: 16/64
Given a stream of raw numbers.
Ex: 5 5 5 3 3 7 1 1 6 6 6 2
How would you store it so that we can save memory?
for example we can group 5 5 5 and represent as 5 3 meaning 5 occurs 3 times
What is a mutex used for?
What is the size of int?
What is a stack?
What is the running time of binary search?
Prove that the order of a selection sort using binary search tree in the worst case (e.g. when the input is already sorted) in O(n2).
Hi has anyone had a recent on-site interview with bloomberg?
could you please share your experiences and probably a few questions that they have asked yu?
Thnks guys...this site has been a real help to me..
You have a large text file. Given any two words, find the shortest distance(in terms of number of words) between the two given words in the file. Can you make the searching operation in O(1) time? what about the space complexity for your solution?
Ex:
File contains:
as was is the as the yahoo you me was the and
Words given: the, was
Answer should be: 0
If Words given: you, the
Answer: 2
difference between Array and link list
Create a sorted singly linked list out of a sorted BST.
What is difference between String and StringBuffer classes.
Write code for the following mode of string comparision. The method should return true if the second string contains all the characters of the first string (order is not important) and you should consider duplicates.
For example, first string is aabc, true for kbaac, abac.. false for abc.
Dont worry about the complexity. I guess the person just wants to see if I can write code. Also I think I got the correct idea in less than 30 seconds but putting it on the board took around 10 minutes.
How do you shut down in linux?
What does a static method mean in Java
What does Synchronized keyword before a method do in Java?
Select a topic of your choice and talk about it for 5 minutes. If you want I will time your talk.
This is a weird question and trying to appear technical I talked about object oriented principles. I covered 6 points from the head first design patterns book and then I asked him am I going in the right direction.
He said that I am above 10 mins and he said he liked what I said.
What is the difference between int and Integer and why is Integer required.
I recently had an interview with Amazon for development support engineer position for the Amazon Web Services team.
Summarizing my interview was mixture of technical and non technical questions unlike for a software developer which seems to be fairly technical. I had 7 interviews and they kept moving me around conference rooms between each interview.
Of these 3 were with the concerned team, 2 were with people in closely working teams, 1 is with an external team member and one is with HR. The first one started around 12.00pm and it was lunch interview(gosh I hate them). It was with the hiring manager and I am thinking that yes/no decision would have been made by that person.
Most of the questions were asking me say how would I approach a imaginary situation and all. Only the last was completely technical.
phone number to character conversion
Write all possible character string that is possible from given phone number
How could a linked list and a hash table be combined to allow someone to run through the list from item to item while still maintaining the ability to access an individual element in O(1) time?
The bigger the ratio between the size of the hash table and the number of data elements, the less chance there is for collision. What is a drawback to making the hash table big enough so the chances of collision is ignorable?
write a program in c language on matrix multiplication of complex numbers
Discuss psuedo-code then implement Shell Sort.
Suppose you have a huge file (few million entries). Each line has a name; an id and age, all three separated by a space. How do you go about sorting this and writing this in a sorted order in another file? Of course you can't read the whole thing in memory.
How many trailing zeros are there in n factorial?
2nd phone interview.
1)what are static functions/variables
2)find the number of times an integer occurs in an array. write code.
3)what is operator overloading
4)what are virtual destructors
5)difference between linked list and array
6)database q's
7)basic unix q's grep ps
Given a binary search tree, Convert into 'sorted' doubly linked list. You should not use any extra data structure and re use the binary tree structure to the doubly linked list.
Given an array of int values design an efficient approach to find if the sum of any 2 values in the array is equal to a 3rd value in the same array.
Gayle please help...
1)Implement binary search in a sorted array if array, size and element to be found is given?
2)arrange from best to worst:
BST, sorted array, unsorted array and hash search based on big O analysis for an average case for inserting, finding an element and finding the range(lowest number and highest number)
3)how would you find the unique lines(that are too long to store in memory) between 2 files tat have a billion lines of data each. How will you find the non-unique lines.
print "google" in binary representation.
Say all amazon employees benefit valet parking in at the office. Model the parking garage with OOD to be able to tell me if it has some more spots, if it is empty, to park and retrieve a car.
The question is intentionally vague for discussion purposes.
I have an array that contains integers 1...n.
I remove 2 elements from that array, shuffle it and give it to a function you will write.
Find the 2 elements i removed.
How would you write the program that predicts words from a dictionary you may want to type as you are typing it from your cellphone text message interface?
Lets say you have to construct Microsoft Live maps from scratch and guide a person standing on Seattle to New York. How do you do the same ?
Lets say you have 1 string of length N and M small strings of length L. How do you efficiently find the occurence of each small string in the big string ?
Given an array having first n ints and next n chars.
A= i1 i2 i3 ... in c1 c2 c3 ... cn
Write an in-place algorithm to rearrange the elements of the array as:
A = i1 c1 i2 c2 ... in cn
XSLT -
<a>
<b val="1"/>
<b val="2"/>
<b val="3"/>
</a>
Print the attrib vals
Given two arrays char *pa, *pb. Write a function to return true/false. True if all occurrences of all chars in pb exist in pa. False if not.
Eg. if pa = czcz ; pb = czzz ; return false coz pb has one z extra
if pa = abaa; pb = ab ; return true
if pa = ab ; pb = ab ; return true
Given an array of integers a[ ] and integer x. Return all values from a[ ] where the freq of integer in a[ ] is greater than x.
Suppose you have a 2^40 integers(4-byte-sized each) in a file, and you have a limited 15M physical memory, write a program to output an integer(4-byte-sized) that is not in the file, or report out there is no such integer.
You have stream of words coming, which data structure should be used to store the words efficiently and to answer word queries and maintain top k high frequency words.
You have given an array from 1 to N and numbers also from 1 to N. But more than one number is missing and some numbers have repeated more than once. Find the algo with running time O(n).
Given a string "foobarfoo", in which "fo" and "oo" are repeated twice. You have to find all such repeated pairs in O(n) time. The string can only have alphanumeric elements in it and code it in C.
Given two binary trees T1 and T2 which store character data, duplicates allowed. You have to devise an algorithm to decide whether the T2 is a subtree of T1. T1 has millions of nodes and T2 has hundreds of nodes.
Describe the types of casting in C++.
I had an interview with Qualcomm about 2 weeks ago (for two days) with two different teams for two different software engineering positions.
The interview was very exhausting with questions ranging from sorting and searching algorithms and their efficiency discussions to coding questions in C, puzzles, device driver, boot loader, Networking questions and embedded and RTOS questions to projects I had worked upon during my Masters etc etc.
Both teams called me after about two days after the interview and told me that they are interested in making me an offer and I would have to tell them the team I am interested in working with. However the offer details came to me about two weeks after the interviews. The whole process was very professional and I am happy with the way they conducted it.
for a try/catch/finally block when is the finally block not executed.
Given a constant number of priorities implement a priority queue with O(1) enqueue and dequeue implementations.
Design an algorithm to find whether a given string is formed by the interleaving of two given strings or not.
s1= aabccabc
s2= dbbabc
s3= aabdbbccababcc
Given s1,s2,s3 design an efficient algorithm to find whether s3 is formed from the interleaving of s1 and s2.
Find the Least Common Ancestor(LCA) of two nodes in a binary
tree. Design an algo and explain the time and space complexities of the algorithm.
To understand LCA, please google it
Amazon in IIIT-H on 7th Dec
1. Given two lists which are unosrted design an algo to find the intersection of the two lists.
Ex
1. 24 45 56 12 34
2. 12 31 14 24 56 67 89
Soln: 24 12 56
The lists are not linked lists. Just a stream of integers.
They are not sorted.
Template vs. Inheritance. Why use one over the other?
Write a smart_ptr class
Compare Hash table vs. STL map
How is hash table implemented?
For a hashtable, if the number of inputs are small, what can be used instead of a hashtable?
How do virtual function works in C++? What if the function is not declared virtual?
You've been running test that seems to cause your computer to slow down each time you run it. For example, after running the test once, everything seems fine. But after several times, every action you do on your computer is noticeably slower. What are possible causes for the problem? For each possibility, how would you figure out if it really is the problem?
Create an object-oriented design for software that allows people to play the card game "War" over the internet. Include the classes, methods, and important variables and data structures in your description.
Create a program that traverses a tree full of nodes and calls a function when it reaches a leaf node.
<node> childnode
a node
+ childnodes
b node
+ childnodes
c node
+ childnodes
x node
d node
g node
p node
Design (classes and class diagrams only) an object oriented Network Library that will facilitate.
1. Making TCP/IP connections.
2. Send and receive messages (Both TCP and UDP).
I would like to see class diagrams and the role and how the interact with other components. Please provide pseudo-code that shows how the classes can be used.
Design (like to see class diagrams) a Formatted File reading System, and provide an implementation. The requirements are as follows.
1. The system must be configurable.
2. Should facilitate addition of new formats quickly.
3. Must be portable.
4. All files are of a standard format. They have several sections. Each section has a header that describes the data that follows it.
MATRIX_1 2 3 <Header>
1 1 1 <Data>
2 2 2
MATRIX_2 1 2 <Header>
1 2 <Data>
(U can use any third part libraries such as boost, ACE etc.)
The question is:
Input: bit stream. Or a byte stream. Such as:
000000000000010000001000
0 1 2
Map table: 0->A 1->B 2->C ...
Output:
Cut every 7 bit,map it to character and give output.
Here for example,it should be:
char *out = "ABC"
I didn't figure out how to process the byte stream with 7 bits easily.May I do bit operation with a string?
Thanks.
how would you convert a given numerical input to roman numeral format???
how would you convert a given numerical input between 1 and 3999 to roman numeral format???
What does O(1) space algorithm mean?
Given two lines on a Cartesian plane, determine whether the two lines would intersect.
Find a square root of a number without using the square root function.
5 6 7 8 8 8 8 8 ? What is the next number in the series ???
Here's one I got asked which kicked my butt. Write a function that takes in an array of n ints from 1...n-1. For example, an array of 4 numbers which all have values of 1, 2, or 3. There will obviously be at least one duplicate number. Return one of the duplicates (EASY!) - Now do this in order n, without allocating ANY new memory (no hash table or anything)..
(Note: I did figure out a solution to this, but the interview didn't seem to like it very much but whatever)..
given a integer, output its previous and next neighbor number which has the same number of bit 1 in their binary representation.
how to divide an integer array into 2 sub-arrays and make their averages equal? e.g. a[left_portion]/left_portion_num == a[right_portion]/right_portion_num.
Given n unsigned integer, output 2 integers which has the maximum result after XOR.
An array A[1...n] contains all the integers from 0 to n except one. In this problem, we cannot access an entire integer in A with a single operation. The elements of A are represented in binary, and the only operation we can use to access them is "fetch the jth bit of A[i]", which takes constant time. Find the missing integer in O(n) time.
Given 2D Matrix of characters; find whether a word is there in this array. It can start at any position and can be present horizontally, vertically and diogonally both in forward and reverse order.
Given 1 GB memory, input a file which contians 4 billion integers, output one integer that is not in the file. What if you have only 10 MB memory?
Input an integer array of size n and an integer k (k<=n), output all subsets of size k.
A bank has a collection of n bank cards that they’ve confiscated, suspecting them of being used in a fraud. Each bank card corresponds to a unique account in the bank. Each account can have many cards corresponding to it, and we’ll say that two bank cards are equivalent if they correspond to the same account. The only way to say 2 cards are equivalent is by using a high-tech “equivalence-tester” that takes in 2 cards, and after performing some computations, determines whether they are equivalent.
Their question is the following: among the collection of n cards, is there a set of more than n/2 of them that are all equivalent to one another? Assume that the only feasible operations you can do with the cards are to pick two of them and plug them in to the equivalence tester. Answer in O(n)
There is a binary expression tree. The leaves of the expression tree hold operands & nodes contain operator. How will you compute the value stored in the tree ?
A) Write a function that will return the 5th from the last element of a singly linked list (eg. the 11th element of a list with 15 elements). Assume that the linked list class only implements two public members: Node GetFirstNode() and Node GetNextNode(Node node) methods. The latter method returns null when the end of list is reached.
B) Explain how you would test your solution.
There are three machines with different processing powers. They each take respectively 2, 10 and 20 units of execution time to finish a task requiring X effort. If we let all three machines work on same task, considering each quantum of task is independent of the other, so that not for a moment a machine has to wait for another one to finish, how long will it take for three machines to finish the given task.
what is booting?
write a code to print last 10 lines in a file using c
Write a code to generate a gray code . Approach is also fine.
On January 1, 2007 two new societies S1 and S2 are formed each with n members. On the first day of each subsequent month, S1 adds b members while S2 multiplies its current number of members by a constant factor r. Both the societies have the same number of members on July 2, 2007. If b=10.5n, what is the value of r?
In a Park, N persons stand on the circumference of a circle at distinct points. Each possible pair of persons, not standing next to each other, sings a two-minute song – one pair immediately after the other. If the total time taken for singing is 28 minutes, what is N?
How do you build address bar in say gmail. i.e. if you press 'r' then you get all email starting from 'r', and if you press 'ra' then you will get emails starting from 'ra'.
How to prevent reverse engineering of DLL?
This was my first question of the telephonic interview,
Suppose there are two functions, Function First allocates a memory and then call Function Second..... But in Function Second Exception occurs!!! How do you notify Function First about this in order to deallocate the memory allocated by First???
You have a random 5 function. Generate a random 7 function using this random 5 function with equal probability
hint: think at bit level
1. Question: A solution consists of four balls from a set of four different colors. The user tries to guess the solution.
If they guess the right color for the right spot, record it as being in the correct 'Location'. If it's the right color, but the wrong spot, record it as a correct 'Color'. For example: if the solution is 'BGRR' and the user guesses 'RGYY' they have 1 'Location' and 1 'Color'. A correct solution would be 4 'Location' and 0 'Color'.
Write a program to, given a solution and a guess, calculate the response that we present to the user.
Question: You are given an array of n integers (both positive and negative). Find the first continuous sequence of integers with the largest sum. For example, {-7, 4, -2, 5, 3, -6, 8, -9} : {4, -2, 5, 3, -6, 8} or {5, -3, -4, -2, 6, -4, 1, 3} : {6}
Explain what the following does: ls | grep a
Recently in one of my interview i faced a question with Cube.The question goes like this.
Draw a cube,on each of the 8 nodes binary numbers is represented.(am helpless since, actually diagramatic presentation will make it sense)
The interviewer now wants to know why or in what fashion he represents the nodes with the binary digits?
Give an efficient implementation of an operation FIB-HEAP-PRUNE(H, r), which deletes an arbitrary
min(r, n[H]) nodes from Fibonacci Heap H. Here, "arbitrary" should be taken to mean "your
algorithm may delete any min(r, n[H]) nodes that it desires".
Analyze the running time of your implementation.
PS: min(r,n[H]) means the smaller value of r and n. r is an arbitrary number, n is the number of nodes in the Heap H.
In a nxn tic-tac toe game with m players. Define a method that runs in O(1) and decides whether for a given move, the players wins or not ?
Given two dices labeled 1 to 6. Take 1 dice and relabel it such that the sum of the two dice's is between 1 and 12. This sum occurs with equal probability. How will you relabel it ?
Coding Exercise:
Write a method that takes a pointer to a Node structure as a parameter. The Node structure contains two pointers to other Node structures. The function should return a complete copy of the passed-in data structure.
For example, the method signature could look like so:
Node* Copy(Node* root);
Note:
· Do not make any assumptions about the data structure – it could be a tree, linked list, graph etc.
· Feel free to choose the language you are most comfortable with (C# or C++ are preferred)
In addition to the function code, write a complete suite of unit tests for this problem.
Has anyone cleared interview in Adobe ?
Implement itoa - takes an integer as input and outputs its string equivalent.
char* itoa(int n)
Given a series of positive integers. Design an efficient algorithm that can detect pairs whose sum is equal to K such that K = ei + ej, and (i not equal to j).
Given an array of sorted strings that also contains empty string at some locations, find a string in this array.
["a" "" "" "" "" "b" "c" "" "" "" "d" ""]
Had a phone interview with Bloomberg... some time back. These were the questions....
1) Difference between delete and free.
2) Why cant one throw exception from destructor.
3) How is exception handling implemented in C++
3a)What is stack unwinding in exception handling.
4) Given two files find the intersection of it in O(n). What if files are too large, i.e. memory constraint.
5) How is fork and exec different
6) How is background and foreground process implemented in unix shell
7) How to bring some process in foreground.
8) How to find if some process is leaking memory.
9) Given a code, where are static, object cretead by new and automatic members stored.
10) What is memory leak and why.
11) What is auto-ptr and how is it implemented.
12) What happens in fork .. expalain.
Write a function that will return the 5th element from the tail of a singly linked list and explain how you would test your solution.
Given a preorder and inorder traversal of a binary tree, can you reproduce the tree? if yes, then write a function using C/C++ that builds the tree and returns the root node of the tree.
How can you unload a .class from JVM ?
Every Amazon development position includes a "support burden," i.e. 24x7 pager duty. They systematically do NOT tell candidates about this (just finished a year there myself.) While on call, you can't really leave home without your laptop, power adapter, cables and ivpn device and you must stay within 20 minutes of an internet connection. Make sure to find out how many in your oncall rotation and average number of pages per week for both your service and your database (most SDEs are level one support for a database.) For some this isn't a problem--just make sure you are informed!
To output the number in a sorted way. The sorting is done based on string sorting and not on numrical. (Eg:121 comes before 2 because the Most Significan Digit is 1 in 121 which is less than 2)
disp(int low, int high);
disp(5, 1113);
Required Output is:
10
100
1000
11
12
.
.
19
101
102
..
so on
He asked for the algorithm with 2 constraints where no space was considered.
Came out with an algo with O(nlogn) : convert the numbers into string using sprintf (for eg) and sort the numbers. Straight answer
he then made the problem complex by having the constraint O(n) in space !.
Approached the probem with recursion but could not get my logic right.
Algorithm to find if a tree is symmetric?
(The tree is a generalized tree with as many child nodes as possible)
You are given an array containing integers and we know that it contains contiguous number (for ex. say 1-25). One of the numbers is repeated. Find which number it is.Come out with the best solution possible. You are not allowed to use extra space(hashing, another array,etc).
There is a blank disc( like a CD). You are given two colors of paint (black and white) . A sensor can recognize the color painted on the disc and produce an output. Paint the disc in a way such that you can find the direction of rotation by looking at the output.
Given an N-by-N array of black (1) and white (0) pixels, find the largest contiguous subarray that consists of entirely black pixels. In the example below there is a 6-by-2 subarray.
1 0 1 1 1 0 0 0
0 0 0 1 0 1 0 0
0 0 1 1 1 0 0 0
0 0 1 1 1 0 1 0
0 0 1 1 1 1 1 1
0 1 0 1 1 1 1 0
0 1 0 1 1 1 1 0
0 0 0 1 1 1 1 0
you are given an array of integers containing only 0s and 1s. you have to place all the 0s in even position and 1s in odd position and if suppose no if 0s excedd no. of 1s or vice versa then keep them untouched. Do that in ONE PASS and WITHOUT taking EXTRA MEMORY.
input array:
{0 1 1 0 1 0 1 0 1 1 1 0 0 1 0 1 1 }
output array:
{0 1 0 1 0 1 0 1 0 1 0 1 0 1 1 1 1 }
if p & p^2+8 are prime, prove that p^3+16 is prime
For the Location: CT, USA
1. describe OOP
2. describe Hibernate mapping that you have been work on
3. describe AJAX
4. What’s the difference between inner join and outer join?
5. Do you have any database design experience?
6. Do you have experience on JBoss
7. Do you have experience on Swing
8. Do you have experience on JMS
9. Do you have experience on SOAP
what is the maximum number of binary trees that can be formed using 3 unlabeled nodes ? explain..
Find the number of trailing zeros in n! where n >= 5.
given an array of integer size N.
a) find all pairs whose some is some given value X.array is not sorted & values are distinct.in o(log n)
b) then interviewer added some constratints..
array is sorted. & values can repeat.in o(n) & space compl o(1)
How do u find distinct intersction between 2 arrays? Come up with a best solution
1: How to find a second largest number within an array without using any loop
2:How to find a missing element in an array in the most optimised way.
There is a circular track.
There are n gas stations of capacity ci.
To go from one station to the next station it takes certain amount of gas gi.
For any station the gas available may not be enough to get to the next station.
Write a linear time algorithm to find the correct station in which we must start in order to complete one round around the track.
Reverse the bits in an incoming bitstream given a function that has its input parameters as a char *ptr and tot_siz where tot_siz is the size of the buffer..
You have three baskets. Basket # has apples,Basket # 2 has oranges, and Basket #3 has oranges and apples.
THe baskets are mislabled.After how many tries will you be able to figure out which baskets have the correct items.
Given an array eliminate the duplicates in the array and print it....linear time complexity
Why is access to static variables not allowed from non-static methods in java?
Given two linked lists, which merge at some point, find the point at which they merge
Give an algorithm of minimum complexity to list the synonymns of a word.
Given two arrays A [1..n] and B[1..m], find the smallest window in A that contains all elements of B. That is, find a pair <l,k> such that A[l..k] contains B[1..m]
For example, given A = 3,1,5,7,3,5,2 and B = 5,3 then the smallest window is [3,5].
Rotate a string (cyclic rotation) by the given integer
Truncate extra spaces between words in a string
How would you design the data structures for Notepad? Specifically, how would you write a string to it efficiently (eg, edit)?
If we have a relative path with .. (means parent directory) and . (means current directory) , write java program to find absolute path?
Ex:
Input:- C:\Dir1\Dir2\..\Dir3\.\Dir4\helloworld.txt
output:-
C:\Dir1\Dir3\Dir4\helloworld.txt
How is synchronization implemented in java ? explain ?
What is the singleton design pattern? Implement getInstance() method for it. What are the potential problems with it?
Design the class for deck of cards.Add methods shuffle and deal.Implement Shuffle.( asked me to finish the stuff and mail the code in 10 mins)
How is the memory layout in an object-oriented language like C++/Java different from the procedural language like C? In C, we store code and data in various segments like data segments, code segments, stack segments; What do we do in C++?
Define any class and tell me how will an object of that class be stored in memory?
Given an array A, how would you create an array B where for each i from 0 to n,
b[i] = a[0] * a[1] * ... * a[n-1] /a[i]
You should do this in O(n) time without using division.
As an example, if A = {1,2,3,4}, B should be (24,12,8,6).
have 1 million customer addresses, how to store and search them efficiently. Suppose you can search the address by phone number or name or account number. My response is to use a hashtable with phone number as the key and address as the value. But how to implement multiple keys to the same value? Any other options?
Given a number, how would you check to see if it can be accurately represented in binary (eg can 76.2782783 be represented accurately in binary)?
There are two people A and B, both are geographically apart from each other and can't meet. They exchange messages through a Box which has two latches and the box is delivered by a postman. Given the chance the postman will break into the box. The box can't be opened if there is atleast one locked latch. Both A and B buy a lock, both get two keys with them (A has lock1 and B has lock2). Now how can they communicate securely using this system?
Suppose the email system of the world crashes, you have the job to design a new system from ground up. How would you do that?
Design an algorithm and write code to see if a tree is balanced or not.
Find the largest 1 million numbers in 1 billion numbers. Supposed the memory can hold all the one billion numbers.
The interviewer said there exist a O(n) solution, anyone has any hint?
(2nd Phone Interview)
You have a file with millions of lines of data. Only two lines are identical; the rest are all unique. Each line is so long that it may not even fit in memory. What is the most efficient solution for finding the identical lines?
Print all combinations of M members of a set of N elements in a sequence such that each set can be obtained from the previous set by deleting one member and adding one member.
Write a function to remove an ANSI string (subject) all occurences of all characters in another string (pattern) and compact the subject in place (without altering the order) For example, if subject is "cdxddeeefce" and pattern is "cex" then the result should be "dddf".
40% of a program will not benefit from additional processors because it is inherently sequential. How many processors are needed to execute a program in 150 seconds, if it required 300 seconds with 1 processor.
Which (one or more) of the following numbers can't be represented accurately in binary?
0.1, 319, 63.5, 1/16, 1.32, 5.390625
Implement a function to check if a tree is balanced, given its root node. i.e. "no two leaf nodes should differ in distance from the root by more than one". use the function prototype-
bool IsBalanced(node *root)
Find the Mth last element of a singly linked list in the best possible time and most efficient use of memory.
Given a Binary Search Tree, find its depth.
You have a billion urls, where each has a huge page. How to you detect the duplicate documents?
Write a function which prints out all valid phone numbers. A phone number must consist of a sequence where the previous or next digit corresponds to a horse move in chess or is a repetition of the previous digit. So an example would be 1672943, 1834927 and 5555555.
Repeating digits are allowed.
A phone number is seven digits long and cannot contain the * or #.
Given a binary code for a number, write a program to find its gray code
Given gray code of a binary number. Write a code to Find the binary number.
Convert Hello World! --> olleH dlroW!
was asked to write test cases and handle special chars.
Two linked lists merge at a point. Find the point of merge.
given an array of integers sorted in increasing order say a[5]={1,3,5,9,15}
now suppose left rotate is done on the array. i.e. if left rotate = 2. it means all the elements are left shifted by 2. so for eg if left rotate applied to above array, array becomes {5,9,15,1,3}..
question is given a left rotated array write a code that tell how much is the left rotation..for example for the above array code should return 2..and so on
Given an input array of size unknown with all 1's in the beginning and 0's in the end. find the index in the array from where 0's start. consider there are millions of 1's and 0's in the array.i.e array is very big..e.g array contents 1111111.......1100000.........0000000
Write code to merge two binary search trees in optimal time
What's the difference between abstract factory and factory?
Design the data structures for a file system
The function (fopen() and fprintf()) returns EINTR when interrupted by a signal that was caught. We want to test this by sending a signal to interrupt fopen/fprintf when it is called. When should the signal be sent?
How would you add two 64 bit numbers on a 32 bit machine?
Given an arbitrarily long string, design an algorithm to find the maximum repetitive substring. For example, the maximum repetitive substring of "abcabcabc" is "abcabc".
Imagine there is a square matrix with n x n cells. Each cell is either filled with a black pixel or a white pixel. Design an algorithm to find the maximum subsquare such that all four borders are filled with black pixels;
"Homework" problem to be done after the phone interview and emailed to the interviewer that evening: Write a program to convert a decimal number to Roman numerals.
Write a function that returns the longest palindrome in a given string. e.g "ccddcc" in the string "abaccddccefe"
Write a function that returns the longest run of a letter in a string. e.g. "cccc" in the string "abccccdef".
write an algo or c prog for postorder traversal of a Binary Search Tree.the algo should be iterative,it shouldnt be recursive
How do you implement three stacks in a single array as efficiently as possible?
Design an BPO company.
1. Company has 3 levels of employee, Fresher,TL,PM.
2. Any incoming call(telephone) has to be allocated to the Fresher who is fre.
3. Call has to be closed in 8hrs.
4. If fresher not able to handle the call, escalate the call to TL.
5. If TL not free or not able to handle escalate to PM.
6. When call is comming it shoulbe be assigned to the Fresher who is free at that time.
for above feattures put an class diagram in place.
Design a musical Juke Box using object oriented principles.
Phone interview.
Projects.
C and Java, they asked preference.
I said i am not comfortable with C++.though worked with VC++ mainly using MSDN.
lot if threads, mutexes, semaphores, static variable, lots on static variable scope.
reverse a string pitfalls.
polymorphism (messed up here).
projects again.
end.
Selected.
Write code (in C) to convert a binary search tree into a sorted doubly linked list. The algorithm should use recursion and should be done in place.
Matched sequence is like {}[(fd)()]. Unmatched
sequence is like [{]}. Give a function to find if a given sequence is matched. Test your function.
Given a value and a binary search tree.
Print all the paths(if there exists more than one) which sum up to that value. It can be any path in the tree. It doesn't have to be from the root.
I have a following table with coloumn structure as shown below:
FROM TO PRICE STARTDATE ENDDATE
Mum Ban 2000 1stjan07 31stjan07
Mum Goa 3000 1stjan07 31stjan07
Goa Del 5000 1stjan07 31stjan07
.. .. .. ... ..
Mum Ban 1000 1stFeb07 28thjan07
Mum Goa 3000 1stFeb07 28thjan07
Goa Del 5000 1stFeb07 28thjan07
Like this it will be for all other months
So write a query in SQL which will show the output as shown below:
Date TO FROM PRICE
1stjan07 Mum Bang 2000
1stjan07 Mum Goa 3000
1stjan07 Goa Del 5000
2ndjan07 Mum Bang 2000
2ndjan07 Mum Goa 3000
2ndjan07 Goa Del 5000
and like this
we have to arrange it like date wise?
1:How will you maintain multiple webservices.
2:How will you configure CVS , or tell me about CVs configuration.
Provide hash function for variable length strings.
Deadlock? Design a class providing lock function which provide lock only if it sees there are no possible deadlocks.
Suppose we have an array
a1,a2,... ,an, b1,b2,..., bn
How to change this array to
a1,b1,a2,b2, ..., an,bn in O(n) time and in O(1) space.
Determine which level has the maximum number of nodes in a N Ary Tree?
You are provided with a stream of integers, design a data structure to store the number of occurrences of each integer.
Explain the trade offs between multi threaded and single threaded programming. Imagine you have N threads and N resources - how do you ensure no deadlocks occur?
You are given a the source to a application which is crashing when run. After running it 10 times in a debugger, you find it never crashes in the same place. The application is single threaded, and uses only the C standard library. What programming errors could be causing this crash? How would you test each one?
Given two numbers whose digits are repersented
by linked list. Add the numbers and put the result in another linked list
given a 32 bit number N and 2 numbers(A & B) that determine 2 different bit positions of N how do you make all the bits between A and B equal to another given integer k.
given (A,B is in the range [0 to 31] and
k<=2^(B-A+1) ( so that k fits between B-A+1 bits). Give an O(1) solution for this
e.g if N=9 ( 1001) ,A=0 ,B=2,K=5(101 then the result should be 1101 (1.e 13)
given a 32 bit number N and 2 numbers(A & B) that determine 2 different bit positions of N how do you make all the bits between A and B equal to another given integer k.
given (A,B is in the range [0 to 31] and
k<=2^(B-A+1) ( so that k fits between B-A+1 bits). Give an O(1) solution for this
e.g if N=9 ( 1001) ,A=0 ,B=2,K=5(101 then the result should be 1101 (1.e 13)
Write a C code to conert a binary search tree to a linked list
Find the Maximum of 2 numbers without using any if-else or any other comparison operator
Phone interview:
1. Mallocing data and memory leaks.
2. STL and C++ basics: advantages of C++ over C
3. Pgm to check whether stack grows up or down. Low level memory stuff
4. Unix stuff: threads, processes, mutexes, semaphores
5. Questions about projects on my resume.
6. Garbage collection
7. Why Bloomberg?
On site:
1. Projects on my resume.
2. C++ basics again (some really obscure questions in my opinion like immutable classes, mutable classes etc. I wasnt sure what to answer)
3. To code the game of LIFE? (google it)
4. Usual HR questions:
a. Why Bloomberg?
b. Toughest problem.
c. A situation where you showed leadership etc.
Given a set of N numbers find the element (which is guaranteed to repeat itself more than N/2 times) in a single pass.
Given a set {1,2,3,4,5,6,7,8,9,10}, write an algorithm that prints out all the n digits or lesser combinations that can arise out of the set.
condition: Successive numbers need to be avoided.
Eg; if set = {1,2,3,4,5,6,7,8,9,10}
and n = 3
It should print
(1,3,5) --> no successive numbers
(1,4,6)
(1,5,7}
(1,6,8}
(1,7,9}
{1,8,10}
(1,9)
(1,10)
.
.
(10, 1, 3)
(10, 2, 4)
so on so forth.
Given a dictionary of three character words
{cat, bat, tad, zee, bed, tem .... etc} and given a three character input word 'hol', how do you transform it into another three character input word 'deb'?
Condition 1: In a given pass, you are allowed to change only one character in the three character word.
Condition 2: The word that forms out of the changed character in Condition 1 needs to exist in the dictionary.
Condition 3: Input word and desired output word need not necessarily exist in the dictionary.
given a set of numbers N, if I choose (N/2)+1 elements, give me an function to which when 2 numbers are input, they are guaranteed to return a GCD of 1.
Given a binary tree, convert it into a doubly linked list in place
give with set of numbers, print such power set
Design an algorithm and write code to reverse a linked list
Write the code to print a Binary tree level by level STARTING FROM THE LEAF LEVEL and then give exhaustive test cases.
eg: 1
2 3
4 5 6 7
Output: 4567231
Given two integers A & B. Determine how many bits required to convert A to B. Write a function
int BitSwapReqd(int A, int B);
write a program to check if the tree is BST
Write a program to generate a mirror (copy) of the binary tree without using recursion.
There are 3 societies a, b, and c. A lent tractors to B and C as many as they had. After some time B gave as many tractors to A and C as many as they have. After sometime c did the same thing. At the end of this transaction each one of them had 24.
Find the tractors each originally had.
Three friends divided some bullets equally. After all of them shot 4 bullets the total no. of remaining bullets is equal to that of one has after division. Find the original number divided.
Given an integer between 0 - 999,999, print an English sentence that describes the integer.
Given 1234, print out One Thousand, Two Hundred and Thirty Four.
without using temporary variable swap two numbers and also reverse a string
what is virtual memory, page fault, thrashing?
Implement the unix command WordCount (wc) using lenguage of your choice. The method takes a string and returns the number of words in the string, number of chars and the number of lines.
How would you design the software that runs on an ATM machine? The software should support operations such as checking balance, transfer funds from one account to another, deposits and withdrawals.
Describe our design process when given a software development task.
Implement a chess game using object oriented design methods.
Describe the data structures you will use for implementing snake & ladder game
i have number of 10 digits lets say
ABCDEFGHIJ
A represents the number of 0's the above number has,B contains the number of 1's the above number has and so on...
Can you find out that number......
int function findValue(int[]arr,int val,intlowIdx,int highIdx)
{
if(lowIdx>=higIdx)
return -1;
int midIdx:=Math.floor((lowIdx+higIdx)/2);
if(value>arr[midIdx])
return findValue(arr,value,midIdx+1,highIdx)
else if (value<arr[midIdx])
return findValue(arr,value,lowIdx,midIdx-1)
else
return midIdx;
}
And
int arr[]={1,2,3,5,8,13,21,34,55,89};
int n=arr.length;
What is the worse case order of execution if a call is made to
findValue(arr,<input from user>,0,arr.length -1)
a: log(n) log is of base 2
b: n**2
c: n*2
d: n
Implement a Gapped Buffer Class.
What is Heap Corruption?
How do you know if a program has Heap Corruption?
How do you debug it?
What is the minimum number instructions required to swap Odd and even bits in an uinteger
Eg
10101010 should become 01010101
Write an algo to exchange the elements of secondary digonal of a matrix.
Which is the best? Java or C#.
How many ways can you paint a cube if you have three colors of paint?
a. Findodd - given ana array of numbers return a number which appear odd number of times.
b. isPrime
c. Garbage Collector.
d. OO model for Elevator, grilled a bit but successfully answered.
e. Find if high bit is set in the integer.
Whenever you open a file, describe all the steps that the OS goes through .. directory list, inum, inode, data sector.
Given a document of text, return the 10 most frequently occurred words in the text.
two link lists starts from head1 and head2 but their some nodes are common as shown below so they end at the same node
like
a-b-c-d-e-f-
g-h-i
x-y-z-w-
write an algo to find the first commom element of the list ie g.
Implement Breadth First Search for Binary Tree.
Implement Find and Delete for binary tree.
How do you solve the 8-queens problem in chess?
(The 8 queens have to be arranged in such a way that they do not mutually threaten each other? i.e. no two queens should share the same row/column or diagonal).
How to find the two numbers whose difference is minimum among the set of numbers
Given an array of integers (+'ve and -'ve), find the subsequence (set of consecutive numbers) with the largest sum.
How one can measure time spent in context switch.
1. Difference between clustered and non clustered index
2. Difference between having and where
3. What is query optimization
Design an algorithm to find the frequency of occurance of a word in a book
Given an list of songs, how to play them randomly without repetition
what is the difference between pointers and references? When do you prefer one over the other?
What is memory leak?
Write code to find out whether stack addresses will be increasing or decreasing in memory?
(Stack which stores local variables in a method etc..)
How do you use hash table to create phone book? How do you handle collisions in hash table?
Well I just fucked up a great opportunity. Oh well, that's not what this sites about:
#1 Which is faster ++a or a++
#2 Implement a class where implicit conversion takes place.
#3 Diff between stringcopy and memcopy
#4 A program crashes before it reaches main. Where would you look for the problem?
#5 What it wrong with this function:
F1(...){
x = new();
F2();
delete x;
}
#6 when implementing a + operation "string + (string)". how would you return the return value, by ref or by val.
Find the minimum angle between hour hand and minute hand in a watch.
Write an algo, code it in C, write the test cases.
Generate a maze. There should be a path from the entry point to the exit point.
Model a chess game
Create a B-Tree given a large sorted array of integers. Each Node should be around 4KB.
When does the Operating Systems do a Context Switch?
What is Context Free Grammar? What is it used for?
What are the differences between User Mode vs Kernel Mode?
How do you determine the size of an object in Java?
How will you find the longest palindrome in a string? I.e. if the string is XMADAMYX, Your code should print MADAM.
Write a program which makes the probablity of getting the even number when a dice is thrown in 72%( some number other than 50%).
Given a file containing approx 10 million words, Design a data structure for finding all the anagrams in that set
-What are DLLs? Why do we use them?
-How does DLL work? Can anybody call methods written in DLLs ?
-What are static and shared Library? Which is fast and why?
Asked me to implement a Garbage collector for C++
Design a chat server
How do you remove the duplicate characters in a given string without using any additional buffer. Give the Algo., write code and list the test cases.
Develop an algorithm for printing different permutations of the string. List out both recursive and non recursive solution.
Given a graph (any type - Directed acyclic graph or undirected graphs with loops), find a minimal set of vertices which affect all the edges of the graph.
An edge is affected if the edge is either originating or terminating from that vertex.
Which data structures would you use for solving Sudoku problem?
How will you determine the page size of a *nix machine using C code ? Hint: Use malloc()
How was the team structure where you worked last summer?
Have you worked in teams in any of your classes?
Why would you use an interface over an abstract class?
What is Garbage Collection in Java. How is it implemented? What kind of algorithms does the garbage collector use? How does it know that references can be collected? What are advantages and disadvantages of garbage collection?
What is the difference between Inheritance and Interfaces? Under what conditions would you prefer one over the other?
What is the difference between arrays and linked lists? What is the advantage of contiguous memory over linked lists?
Write a function getQuote(string ticker) that retrieves quotes generated no more than an hour ago.
Given two nodes a and b, write a function that returns their closest 'parent' node (must have both a and b as 'children').
Suggest an algorithm to find the first non-repeating character in a given string.
Implement an algorithm to print out all files below a given root node.
How would you design a mutex?
What are your business goals? How do you put them in paper?
Given an unsorted array of positive integers and an integer N, return N if N existed in the array or the first number that is smaller than N.
Give a O(N) algorithm.
You are given an array of integers and a sum. Find all pairs of integers that equal that sum. Assume you have some sort of data structures that will be able to store the pairs. Write an algorithm to find all these pairs.
Try to think of the non-trivial solutions
Why are you interested in working at Sophos?
1)How do you design a new network interface card( bladeserver)? independant of other factors
2)Find out the number of Dunkin donuts in MA?
What is Introsort?
What are the advantages and disadvantages of function lining?
Write code to implement a queue using an array. How do you identify if the queue is circular?
write a program to find whether the m/c is big endian or little endian
What is a scripting language? Write a code to output the dot product of two files.
If there's a glitch in the system and for some reason, for a very brief moment, the website is inaccessible from your browser. You got back to it a few minutes later and the glitch is gone. Would you report this problem?
How do you resolve a collision in a hash table
Design a game of chess/checkers/football. I opted for football since am not very familiar with the other two
Implement C function strtok without making different sub string copies of the original string. Repeated calls will pass NULL as an argument.
Implement :
char *my_strtok(char *src, char *pat)
where pat is any delimiter combination.
Given a roman numeral string, like LIX, print out the corresponding integer value. We discussed different pattern rules before he asked me to write the code.
I - 1
V - 5
X -10
L - 50
C - 100
D -500
Given a node in a binary tree, find the next largest node.
Given an integer, exchange the Most Significant Bit with the Least Significant Bit and vice versa.
Write a method to find if a year is leap or not. If a year is divisible by 4 or 1000 it is leap but only years divisible by 200 are not leap.
Given a string s1 and a string s2, write a snippet to say whether s2 is a rotation of s1 using only one call to strstr routine?
(eg given s1 = ABCD and s2 = CDAB, return true)
(given s1 = ABCD, and s2 = ACBD , return false)
Describe TCP Hand-shake and optimize SQL.
Name all the registers in the X86 machine.
A phone screen. Write a atoi function for decimal. Expected me to "tell" the code right
from "declare a variable i of type int" to the actual logic. Once this was done generalize it do the atoi for any radix.
Create a copy of an existing binary tree.
You have a large unstructured tree, n nodes in depth and m nodes in width. Find the nodes that are similar.
Why do you choose DFS over BFS, and vice versa. Give reason.
You have a HashMap that contains a list of words and no. of occurences, extracted from a page like:
is 10
I 20
are 5
You need to design the page (as close as possible)using this information.
Write a small program that takes two strings as input and prints two
numbers (n1 and n2) as output, where:
n1 is the number of letters in the first string that each has a match in
the second string in the same position in the string.
n2 is the number of letters in the first string that each has a match in
the second string but does not have a match in the same position.
Note that each match is unique. That is, no letter in either string can
participate in more than one match.
I.e., each letter instance can contribute at most once to n1+n2.
Some examples:
abc abcd -> 3 0
aab aacd -> 2 0
aba aab -> 1 2
aba bab -> 0 2
Suppose you have an NxN matrix of positive and negative integers. Write some code that finds the sub-matrix with the maximum sum of its elements
What's your hobby? (For example: reading). Ok, since you know a lot about books because you like to read, how would you test a book?
Given an array A[string], an array of strings where each string represents a word in a text document. Also given 3 search terms T1, T2, and T3 and 3 corresponding sorted sequences of integers S1, S2, and S3 where each integer in Si represents an index in A where search term Ti occured (i.e. S1, S2, and S3 contain the locations of the search terms in our array of words).
Now find a minimal subarray of A that contains all of the search terms T1, T2, and T3. Extend this algorithm for an arbitrary number of search terms. (Hint: Think of the brute force algorithm first.)
You are given n variable length lists. Give an order n algorithm to find the intersection of these lists.
What is the prerequisite for binary searching?
What is an index?
How do you or what is your experience when learning a new language or technology? Mostly from school/work or..?
How would you implement interfaces in c++?
Follow-up to the triangle question.
Now that you have your isTriangle() function, write out as many test cases for the next 10 minutes.
Write an algorithm in a familiar language or in pseudocode that takes three coordinates and determine if they create a triangle.
Develop an algorithm to find out all valid combinations of n brackets. Like for n =3 possible combinations can be ((())) or ()()() or (()()) and so on.
What is Perfect/Universal hashing?
Given a stack S, write a C program to sort the stack (in the ascending
order).
We are not allowed to make any assumptions about how the stack is implemented.
The only functions to be used are:
Push
Pop
Top
IsEmpty
IsFull
Write code to determine if a given square matrix is a magic square (each row, column, and diagonal has the same sum).
I was given a set of data structures and a set of complexities for search and insert operations, and asked to fill in the right ones.
Before doing that I was asked, "given the possibility that a mad monkey was asked to match the data structures with the corresponding complexities what is the probability of him getting it right, assuming he could pick the same complexity over and over again?"
Traverse the leaf nodes of a binary tree.
Implement a jigsaw puzzle in C++. Design the data structures and explain an algorithm to solve the puzzle.
Given a sorted array of n integers that has been rotated i(unknown) number of times, give a (log n) algorithm that finds an element in the array.
You are given a 2-dimensional integer array Arr[M][N]. A few of the elements in this array are zero. Write an algorithm such that if A[i][j] is zero, all the elements in row i and all the elements in column j should be set to 0. In other words, if any element is zero, its entire row and column should be zero.
You are given a singly linked list. The task is to swap every pair of nodes i.e node 1 & node 2 have to be swapped, similarly node 3 & node 4 ..
write code to implement itoa()
Given a simple recursive grammar, design a Parser for it without using recursion.
You are given a MxN integer array Arr[M][N] with a few non zero cells among them. Cells Arr[0][0] and Arr[M-1][N-1] are both non zero. How do you find whether there exists a path from Arr[0][0] to Arr[M-1][N-1] such that all cells in it have non zero elements.
Note that a cell can have at max 8 neighbors, and you can only jump from a cell to one of its neighbors.
Reverse a doubly linked list.
You have to design a database that can store terabytes of data. It should support efficient point queries. How would you do it ?
What's the difference between a primary key and a unique constraint?
How do you model a many-to-many relationship?
Discuss the usage of a foreign key.
How do you enforce referential integrity in SQL?
What are some of the security concerns in web programming? Discuss some of the validations that need to be done in web programming.
How do you pass information from page to another page in ASP.NET?
If I want to bind just one table to my list, do you use a DataAdapter or DataReader?
How do you put the data from a table to a dropdownlist in ASP.NET?
What is a dataset?
Write code to determine the last occurance of a particular character, given a sentence of words (Recall: do not jumpt to a solution, ensure it is optimal)
Questions about the previous versions of the product the group I was interviewing for had developed - what I liked and what I did not (I feel comfortable not revelaing this). Word of advice: Know the group you are interviewing with. I did, and it did com in handy
Explain your current work; clarifications about specific segment of my current project (This was not a happy outing!)
Write code to insert an element into a doubly linked list, given that you have a global tail
Test this (hands me a white board eraser)
Write code to detect whether or not a given number is prime
What's a virtual deconstructor?
Write code to find the sqrt of a number without using any library functions
Explain several different CPU scheduling algorithms.
Imagine you have a listing of student names and marks. Give the best data structure to store the same. Now imagine that you have range of student names starting from a to l, m to z. Use a data structure for such a layout.
Explain what a virtual function and virtual table is
What is a void pointer. How will you convert this pointer to an integer pointer?
For a balanced binary search tree find the number of leaf nodes for a tree with depth 10.
How much memory will the following code take.
void example
{
int bytes;
virtual functionName{ };
}
Design an algorithm to find the 100 shortest distances to stars in the universe
Given an outline for an architectural plan, automate the loading of the design into a computer
How would you design a parking garage?
Write code to delete a node in circular linked list
Write code to find n-th to last node in a linked list
What's the latest book you've read?
What's the difference between == and Equals()?
What's the difference between virtual methods in C++ and Java?
Suppose there is a problem with calculation of taxes on the amazon.com website. How would you isolate the problem. Once isolated and fixed, how would you go ahead and test it?
Discuss the code of pre-order traversal of a tree.
If you are already working why are you still looking?
What is Polymorphism?
Discuss the important features of Object Oriented Programming
What is a tree? How do you traverse a tree?
What are object oriented programming and polymorphism?
Write a program to multiply 2 really long numbers
Write code to reverse the order of words in a sentence
What do you look for in bloomberg? Will you be happy with maintainance work?
Tell me one time when you thought you were doomed but you came out of the problem and how?
When should you use Quicksort, Mergesort, and Heapsort? What are some advantages one has over the other?
What is a recursive mutex lock?
What is the "placement new" operator in C++?
Write a function that takes an integer and outputs whether or not it's prime.
What happens when you type a URL into a browser?
Design a web crawler. Avoid indexing web pages more than once.
There is a building of 100 floors. If an egg drops from the Nth floor or above it will break. If it's dropped from any floor below, it will not break. You're given 2 eggs. Find N, and minimize the number of drops for the worse case.
What is buffer overflow and how do you exploit it?
Explain the relationship between Equals and Hashcode in Java.
Given 2 squares on a 2 dimensional plane, find a line that would cut these two squares in half.
How do you merge n sorted lists with average length K in O(n*log(K)) time?
A defect has been missed out in pre-relase testing, and that defect has been found by a user/customer.
How do you handle the issue, and in what way do you need to communicate to the client regarding the missed out defect?
A geometry/math problem:
Given a triangle and two intersecting line segments within the triangle, find the angle made by the intersection of these two segments.
How do you implement polymorphism in C?
What is the difference between an interface and an abstract class in languages like Java and C#?
Define polymorphism, inheritance, abstraction, and encapsulation(asked 2 more times).
Given eight balls, one of which is heavier than the rest, and a balance scale, what is the minimum number of balances necessary to find the heavier ball?
What if there are three balls on each side, but one is heavier?
What is a virtual function in C++/Java? Interviewer drew virtual func prototypes and asked when would each be called.
What is a design pattern? Name a few.
What is garbage collection?
What is synchronized in Java?
Why do you want to work at American Airlines? What extra-curricular activities have you participated in? What are your short/long-term goals?
Interviewer wrote code fragments w/ try,catch, finally and asked if finally would be executed in different situations. Asked what happens when a catch rethrows an exception w/ respect to finally?
On-site interview consisted of 2 individual interviews. First was hands-on, second was a p2p questionaire.
The format of on-site interview should be the same from year to year for Technology Associate Training program. First, a 30-minute, 40-question diagrammatic test for which you cannot prepare. The test roughly looks like this: http://irisharmy.shlsolutions.net/DIT6.htm
Next is panel Q/A session, in which 3 former Technology Training program trainees will talk about their jobs and answer questions.
The technical questions they asked really depend on what you said on your resume and who is the interviewer. I've seen people was asked brainteasers or details of how DHCP works.
Next will be three interviews, each of which is 45 minutes. All of three interviewers were from IT department. Two of them are VPs and one is an Executive Director. One of the VP only asked Fitness/Behavior questions and the rest were all technical stuff.
Next is called "group exercise." Five to six interviewees are grouped together. The task is to build something (e.g. a toy, an icecream storefront) by using Legos and then to give a sales pitch presentation to a Board about your product.
String XMLEncode(String str). There are a few characters in XML that can't be represent and need to be replaced with a certain special string.
For small dataset (less than 200 elements), why is unsorted array has better performance than binary tree? This wasn't the case 20 years ago. (Hint: It has to do with computer architecture.)
Write the code for quadratic equation.. The equation is given. I identify all the corner cases.
Networking Questions. Design a chatroom.. allow encryption.
Write the macro for Exclusive Or logical operator.
Find first non-duplicate character in a string
"abcda" -> first non-duplicate 'b'
Write a function that would find the one value that occurs an odd number of times in an array. ie; function would return "r" if "ttttjjrll" is passed in.
If you are given a number as a parameter, write a function that would put commas after every third digit from the right.
How would you do a design of a monopoly game (later changed to a chess game)?
How would you design a file system using class diagrams and what data structure would you use?
If you are given a set of 1000 integers in a set A , and 10,000,000 integers in a set B, how would you create a set C that would only contain numbers that are both in A and B?
In a general tree, how would you find the lowest common ancestor of two nodes that are given to you as parameters?
When would you create an interface class.
How would a copy constructor behave if the class had an Object as a member Variable?
There are two large tree (not binary) having n nodes deep and m nodes breadth. (m,n are arbitrary). Again each sub nodes have multiple nodes. Find the similar nodes that have the same data in both the trees using any data structure. Also optimize your algo if there are duplicate values.
Why is OO good?
What is an ER diagram? What is an entity and relationship?
Describe a few software processes. Compare/contrast variants of Waterfall and why/when would you use each? What process would you use to mitigate risks?
Given a calculator that only has the + operator. How would you implement *,-,/.
Questions about C++/Java and Design Patterns.
Design the classes for Tic Tac Toe. Implement make next move method for the computer player and make sure that the computer wouldn't lose.
Design the game Othello. Write the code to check whether someone has won the game.
Design the classes and data structures for a parking lot
Implement class Stack using a linked list.
void removeChars(char *str, char *delete). Remove characters in str that is in delete.
Find nth to the last node in a single linked list.
Look within the book. Each person can look at 20% of the book at a time. Only 70% of the book can be served to all users. Design the data structures for this.
Questions about my research in details
What's hashmap in STL? How do you use it? When would you use it?
What's the difference between a pointer and a reference?
Explain the following terms: virtual function, virtual class, pure virtual function
How would you discover a memory leak in a software product that contains thousands of lines? I said build a reference table for dynamically allocated variables, similar to one java does, and he seemed OK with that.
How do you distributed hash tables work?
Blocking and non-blocking sockets. When would you prefer to use one over the other, and why?
Difference between a mutex and a semaphore. When can we use one but not the other?
How could a computer inside a NAT get the external address of its gateway router?
Differences between C & C++? Give an instance of C code that won't compile under a C++ compiler.
How would you syncrhonize access to a critical section without using library functions (i.e., mutexes, semaphores, ...etc.). Ans: use spin locks.
Write a sorting function...
Explain the difference between: static, global, static within function,vlocal within function
If we make you an offer when can you join? and what is the pay you expect?
Diff between C++ and java
Tell me the toughest problem you faced and how you solved it?
Which data structure would you use if you want to retrieve data in LIFO order ?
What is a Vector class in Java ?
What is a Singleton?
Which data structure would you use if you want to search for it in O(log n) ?
You have an array with numbers 1..n. You don't know the value of n ( It could be extremely large). The maximum value that a number could have in the array is 32,000. There could be duplicate entries in the array. You have 4KB of memory available. How would you use this memory to find out if a particular number exists in the array or not ?
What is a nested class in Java ? Why would you use a nested class ?
Given a sorted linked list, write code to insert a node into this list.
How do you remove a cycle in a linked list with/without modifying the list
Reverse a linked list
Give a sentence, find a specific word occurs in it
Plenty of behavorial questions like what would you do if you found a bug in piece of software that was from a different product group ? If you were short of time, would you release a product with lesser features but bug-free or with all the features but having bugs in them ?
Who is considered as the "Father of Java" ? and why was it invented ?
Lunch interview was with the PM and he asked me to explain the architecture of the product that I had worked on. We discussed some issues with some of the features that he was interested in. Then he gave me a situation where he has 2 huge .dat files with some customer data uniquely identified by a key; there could be some redundant information in both the files (common keys). How would you merge them into a third file ?
Plenty of behavorial questions in this interview too
Differentiate between Array and Linked List
Given the product that I currenly work on (web-based application), how would you test it
Given a linked list, find the middle node of the list
Interviewer showed me a snapshot of their application UI and me how to test it
Interviewer wrote down a function signature DelLinkNode(node* head, int n) and then asked me to explain how the function would delete the nth node from the end of the list
Next interview was with a guy whom the PM reports to. He asked me questions on my resume.
Gave me 2 tables and asked to select data in an efficient manner. This would require a nested select statement and then an inner join on the tables
next interview was with the head of another team in the same group. He asked me to design and implement the BigInt datatype in C++. This datatype should be able to perform mathematical computations on arbitrarily large integer numbers. There is no limit to the size of the integer. Had to design the class, with the constructor and then implement the '+' operator. Also had to completely test the class out.
You are given a hash table with 256 buckets. You want to put unicode characters into this bucket using a suitable hashing function. What would you observe and how would you resolve the issues ?
What is a static member function?
What is an abstract class?
Count the number of set bits in an integer - gave him 4 different ways to do this.
Implement Atoi(char *str)
Reverse all the words in a string.
Merge two sorted array
difference between process and program
if you are not able to identify errors just by discussing with client and customers, what would you do?
tell me about an experience where you had to introduce a new concept to a group of people and win their support
toughest project till date
Gave a puzzle where if there are two screws and a frame tied with a rope to the screws, design the system such that if one of the screws are removed(with second screw in place) then the frame should stay and readjust its position and if the other screw is removed it (with first one is still in place), the frame should fall down. The rope should touch BOTH the screws in the architecture.
Now design the same system in a way that if any of the screws of are removed then the frame should fall (again the rope should touch both the screws)
what is the problem with following initialization:
int i = 1l
int j = oxFFFF;
(answer is portability)
how would you accomodate changes in the system if the requirement changes in the last moment
how will you adjust yourself in a fast paced environment
Why Motorola?
how will you motivate an employee to work
tell me about an event where you failed brutally - how did you convert it to a learning experience
What would your closest friend/relative say about you that you normally wouldn't tell people?
What'd you want to do at LM?
What could you create with unlimited resources?
Puzzle. Given a subset of natural integers {1,...,8}, place them on squares so that no two squares are consecutive in any direction. The diagram was arranged as 4 squares in the center, 2 above, 2 right, 2 left, and 2 bottom. Told me to find at least one solution. Ran out of time on this.
Describe a best software product?
Given a linked list of n elements. Swap(reference swap only) every group of k>=1 elements starting from the first element. Ran out of time on the swap procedure. Told me to show how far I gotten.
Implement int strcpy(char* des,char* src) that returns the # of chars copied. I used ptr notation. He said, how else can it be implemented? I responded arrays, but both are base-offset anyhow. Very simple. I guess he just wanted to see if I know C programming.
What do you envision Cisco people do?
Have you taken any networking classes? How strong are you in C?
Solve puzzle. People(costs: 10,5,3,2,1) trying to get across a bridge within 21 mins. It's dark and only one person carries a flashlight at any point in time. Two people must cross the bridge, since one has the flashlight. How can they call cross the bridge before it breaks? Solved this after he gave me the clue that 10,5 should get across and stay there.
Maxdepth of binary tree recursive and iterative solution.
Define the following terms: static and dynamic binding, virtual table
2 interviewers. One presumably HR and the other definitely tech oriented.
describe a project you worked on. How did you go about designing it. Why do you use stored procedures.
What are differences between java and C#
what is polymorphism
Asked my oppinions on Javascript and other client-side web technologies (the answer that they want is that you should AVOID them at all costs)
Asked for my knowledge of encryption methods
The position was intended for an individual in strong in PHP/mySQL, so many questions were concerning PHP.
Asked for examples of some of my previous web designs.
HR questions:
- functioning in a team
- most challenging work, etc etc
interview 2: [with MSI]
1) copy a linked list
2) modify the problem as follows: add another pointer to each node of the linked list.. call this pointer 'random'... this might point to any random node in the linked list... now copy the linked list.
interview1 [with MSI]:
1) 8 sq problem: high level algorithm
2) detailed code for merge sort
interview 4:[windows media player]
1) determine if a number is a power of 2
2) give a high level oo design of a linked list
interview 3:[windows media player]
given a tree represented such that
each node has a pointer to the parent, its leftmost child, and right sibling. write a code to determine the immediate right node in the tree
Insert a node into a linked list
How would you sort an array that consists of only zeros and ones in only one pass?
How do static variables differ in C and C++?
How would you bring the effect in c++ of static functions without using static?
What data structure did you use on your previous project? Why? How would you improve on that?
How would you bring the effect in C++ of static functions without using static
Where do you see query plan?
(SQL) What is an index?
HR: OOP
How does the compiler manage virtual destructor?
What is the difference between a struct and a stack - in C++ and C#?
Some ways to handle thread.
Synchronization and its benefit. Asynchronization and its benefit.
Difference between array and linked list.
The pros and cons on both (array and LL)
Difference between readonly and const in C#.
Define virtual function.
What is polymorphism - explain in terms of C#?
Why do we need C++?
What is VTable? How its organised?
Difference between encapsulation, abstraction and information hiding?
What is a Singleton class?
What is signature of function and operator overloading? Why do we need it?
What are templates? What is benefit of having template? And trade off between template and overloading?
What is need of virtual destructor?
How do u load dynamically a DLL?
How do you handle unmanaged code in .NET?
Explain garbage collection in C#
Given a new switch /x to the DIR command in DOS. Write a program that will take in this command and then sort the files in a folder by the first word in the first line of the file.
So if file A has "Beginning" as the first word in the first line and file B has "After", the sort order will be file A then file B. (I would be interested in hearing different solutions on this question in particular)
What do virtual destructors in C++ achieve?
Why do you want to be a tester?
Why Microsoft?
#2 Number are generated randomly and stored in an array. Write a program to find the median value of the array as and as new numbers are generated. Improve your solution.
#7 Write a program to find the column's value of a given column from MS Excel. [Ex: - A = 1; B =2, … Z=26, AA =27 and so on]
#6 Design an explaing an algrothim to find the nearest gas-staion from any location in the city/block.
#4 There is an array of ‘n’ integers. Write a function to find the largest number? Do it in one iteration? Now in the same pass also find the 2nd largest number.
#10 There is a list of Customers and another list of Customers who paid. Find the list of Customers who did not pay? What Data Structure would you use ? Why ? Could you Improve your solution ?
Design an algorithm to find the nearest gas station from any location in the city/block.
Design a random number generator such that it selects ‘m’ random numbers from an unsorted array of ‘n’ elements, where each element has equal probability of being picked. A number picked cannot be chosen again.
#1 There is a linked list. The last node could point back to any node in the list (including the head). Find the node in the list to which the last node points. Or in other words at which node does the circular linked list start.
#8 Compare Linked List versus ArrayList.
#5 There are two sentences. Find the common words in the two sentences.
Given the path to 2 directories (say P1 and P2) in the file system write an algorithm to move the directory denoted by P2 to P1.
Prove that the number between any two twin primes is always divisible by 6.
Write and algorithm to implement a Queue using 2 Stacks and write test cases for it.
If a 2-d matrix were to be represented in (a) row-major order and (b) column-major order, what would be the corresponding index given the indices of the 2-d matrix?
Given a sorted (non-decreasing order) array, write an algorithm to create a binary tree with minimal height. Do this in O(n).
[Behavorial] What qualities would make a good manager?
Name a few differences between C# and Java.
[Behavioral] Which negative situation did you encounter in school and how did you deal with or overcome that situation?
[Coding] Define {relatively complex programming term (ie. Virtual inheritance, polymorphism}
[Round 2] {algorithm} There was a timed exercise which had patterns (and shapes) where you had to determine the next in the sequence. It was basically a bunch of logical puzzles to solve in 30-60 minutes (not sure the exact amount of time).
There was a group project where you work together with others with time constraints in order to build something out of straws and pins. You then present it complete with posters.
[Round 1] They may ask from a language you don’t know about to see if you can do something. For example, I was asked about working with a hash table in PERL even though I really wasn’t familiar with it then. He supplied some basic syntax and asked what a statement would do.
[Round 2] You will likely be coding on the board in your preferred language in front of someone who has a pretty good understanding of that language. I was asked to code up a Fibonacci function with the one constraint being that I couldn’t write a recursive function
[Round 2] There will generally be more nit-picky syntactical questions from the languages you do know.
[Round 2] For those who use/like C++, they can tend to like to ask you to describe the minute differences between C and C++ at a low
Given a singly linked list, delete the kth node from the end. Optimize your code.
Write code to find the largest sub-sequence sum in a list of integers (+ve as well as -ve)
Design a web crawler.
Asked to write exhaustive test cases for the above code fragment
Given a doubly linked circular linked list and a pointer to any node and a number 'n'. Starting from the given node, keep on deleting the "nth" node till one node remains. Return a pointer to that node.
Very detailed questions on all projects mentioned in my resume. Design level and implementation level questions on all projects.
Asked to thoroughly test a given windows form.
Token a string on the basis if a given delimiter.
e.g S is the base string and D is the delimiter (could be a sequence of any valid chars)
S = ["who is the man who saw the eagle today went the wrong way?"]
D = ["the"]
Result = ["who is ", " man who saw ", " eagle today went ", " wrong way?"]
Asked a lot of questions on my Thesis. Asked about the implementation, the performance issuses and how I would scale it.
Given specific scenarios about the product the group was working on. Asked how I would test it.
Write a function that returns a running average everytime it get called. Make provisions for multiple processes to call this function.
Questions on low level networking, how packets are ordered, how are headers used, how are packets fragmented, how do broadcasts work. Also some questions on Client/Server Communication
Lots of resume related questions, going deep into every project.
3) What are memory leaks ? what tools you have used ?
4) Whats the size of integer, double - basic questions ?
5) How will you determine the size of an variable without using sizeof operator ?
Ans: Basically get the difference on the pointer address for the current and the incremented position and storing the difference on data type ptrdiff_t.
6) whats the difference between malloc and calloc ?
7) whats the difference between new and malloc ?
8) whats a virtual function ?
How would you get a process listing in a unix box? What about for a particular user?
Whats the difference between a pointer and a reference variable?
What's the size of a empty class
class { }
11)Inline function
12)Cast data types in c++
Various lot of simple basic questions.
Phone:
write a program to reverse the bit representation of an integer
questions abt stack/heap/recursion etc.
Write code to reverse a doubly linked list
Interview #4 Chief Technology Officer Another BS session. Why do you want to work for us? Description of what they do, how much money do you expect...
Interview #3 Product Manager Asked a variety of knowledge based questions about networking and my skills.
Design an algorithm to shuffle a deck of cards, given that the cards are stored in an array of ints.
On campus interview: Was asked to explain boxing in .NET, the difference between C and C++ and other knowledge based questions.
Interview #1 Developer spent time asking about previous experience. This was a BS session.
Count the number of set bits in a byte
Remove duplicates from a sorted array
Write a program to calculate the nth Fibonacci number.
Design an algorithm to figure out if someone has won in a game of tic tac toe.
How will you determine if a loop exists in a link list?
Write code to convert an IP address into a DWORD
How will you merge two sorted arrays. The first array has enough empty spaces to accomodate the second array.
Asked about Polymorphism
Given a sorted array of n integers that has been rotated either to the left or to the right by i places, give an algorithm that searches and finds an element in the array in log n time.
What is your passion?
Adding and deleting nodes in a circularly doubly linked list
Design test cases for the same
HR based questions: Why MS; Why testing
Qualities of a good tester
OO questions: Polymorphism, Inheritance, Encapsulation
Convert the linked list you just created into array elements. Strangely enough, the interviewer insisted that a[10] does NOT create memory and "malloc" had to be mentioned, explicitly! (Not a happy outing here, again)
Given a website with a textbox and a sumbit button. Type in any webURL to display an ad on MSN homepage, if it is not already present. Test this.
Given a binary tree of integers, What is the average? average = sum/count. What if the binary tree has a loop?
Given a binary tree where each node's value is a COLOR. A clump is formed when more than 3 COLORS are adjacent to each other. Return the total number of clumps in a binary tree.
What is consistent hashing?
What is a virtual method?
Assume that you are working on a small device which has a CPU with no MMU (Memory Management Unit) and a limited amount of memory (1M). We want to be able to run apps on the device that may need more than 1M throughout their execution, although they never need more than 1M at any particular instant. We are in control of the operating system running on the device as well as all tools, compilers, linkers, etc. Discuss ideas on implementing a virtual memory management system on the machine.
What data structure would you use if you were asked to find the top 10 most frequent words in a file? Assume that you have a file parser that has a GetNextWord() API.
What is REST (Representational State Transfer)? What are the fundamental principles?
-Is RPC an example of REST?
-Can someone use the principles of REST over SOAP?
What is an HTTP redirect?
When do you think that a project is successful?
Similar questions..
Questions abt projects in resume, behavioral questions, team management questions.
Write a program to shuffle a deck of cards. Write your own random function. How will you make it more random? It's basically used in a casino, so it has to be AS RANDOM as possible. How can you make sure that no one sees your random function?
Questions on C++, templates, auto_ptr etc.
Given a character array, print all the subsets of those characters
Design the data structures for a deck of cards
Onsite: How do you determine the starting point of a loop in a linked list? Write code.
What's the worst case runtime for this?
Write a program to find whether a machine is big endian or little endian
Write a program to check whether the given two logical addresses are in the same page.
Design question, brainstorming: Design a system / give algorithm : There is a user and a browser. The intranet has lots of machines but their internet connections are slow, 2kbps. How do you use these machines to improve the user experience? Also, devise a way to precrawl and cache the pages that are linked to the current page. Trade offs/ design choices etc.
Given a binary search tree and a keyvalue, return the node that has value closest to the key.
Given two leaf nodes in a Binary Tree (Not Binary search tree), determine the first common ancestor of these two nodes.
Asked to code the 'floodFill' method used by graphic products like Paint.
What is the benefit of using StringBuffer?
What log file can you refer to for determining if a JUnit test failed?
How does Struts implement MVC?
In Java, if we insert a return statement inside the try block of a try-catch-finally, will the finally block still get executed?
Other questions as came up during the conversation ... total of 45 minutes on the phone. Informed me that HR will be in touch for a 2nd technical interview.
What other design patterns have you been exposed to?
What is the difference between SAX and DOM? Which API provides a faster implementation?
How would you shallow copy an object?
What is Singleton design pattern, and how would you implement it?
3 1 3 6 = 8
Add operators (only + - * /), parentheses, etc. to the expression above to make the equality true.
Given a circular linked list where the length of the stem can be arbitrary (the shape of the list can be like number 6). What is the size of the list?
A file contains millions of 30 bit binary numbers. Write an algorithm to efficiently place the pairs of numbers that are compliments of each other into another file.
Write an algorithm to find the 9 digit number without zeros containing distinct digits from 1 to 9 such that the number form upto to the nth digit is divisible by 9.Ie the number formed by 1st and 2nd digits must be divisible by 2, the number formed by 1 to 7 digits is divisible by 7 and so on.
What are thread, why are they used in programming?
Difference between polmorphism and inheritance?
Algorithm and code to detect occurence of a string(patterns) in another string ex: aab, aababa
Difference between class and object?
OO design related question? How would you design a class structure for animals in a zoo
Homework: Reverse all the words in a string.
why cs
If there are two structs, TreeNode and Tree. TreeNode contains 3 elements, data, lChild and rChile. Tree contains 2 elements, int size and TreeNode *root. The tree is a complete tree. So how to find a O(logN) approach to insert a new node.
Brainteaser: there is a bar with 25 seats in a line. The people there are anti-social so when they walk in the bar, they always try to find a seat farthest away from others. If one person walks in and find there is no seat are adjecent to nobody, that person will walk away. The bar owner wants as many people as possible. The owner can tell the first customer where to sit. all the other customers will pick the farthest possible seat from others. So where should the first customer sit.
Design a data structure for storing sparse arrays. Implement multiplications of such arrays.
int[1000], numbers from 1 to 1000, but one is missed - find it
array vs list
reverse linked list. Why don't you use recursion?
what kind og job do you prefer
Discussed the proof and solution to my card shuffle problem
Design the data structures and algorithms for a LRU (Least Recently Used) Cache
I took around 2 hours to do a good job for this becoz he wanted propper OO concepts. Created the util class as a singleton with synchronization for the add and edit methods with exceptions being thrown when employee's arent found etc. He seemed to like it from the reply mail i received
Asked me to describe the difference between final, finally and finalize in java. (The last one is tricky coz we rarely use it)
The hardest question to date on a phone interview. he asked me to take 2 hours and write the following API.
Create an LRU Cache that caches some key/value pair and kicks out the Least Recently Used when you run out of space. Wanted run times and asked me to comment on how good my implementation is and whether its good for industry level usage.
When i wasn't certain whether my random function generated with equal probability all permutations, the interviewer asked me to write a formal proof that it works or not and send it to him (really strange).
Proved it with the following and he bought it:
Probabilisticly
card 1 has 52 positions it can fit in
card 2 has 51
card 3 has 50
so on and so forth
card 52 has 1 position to fit in
hence its 52 x 51 x 50 x ... x 1 = 52! can be generated using this shuffle.
Oblivious to me, aparantly this kind of shuffle is used a lot in online card games. Silly me :P
Define "class" and "object."
Asked me to reverse a Linked list without re-creating a new one. I did it recursively going all the way to end and linking it backwards after the recursive call. Had to pass in two nodes though, one previous and one current. He said he likes iteration better becoz its more resource friendly :)
What does the keyword "final" do when put in front of a Collection in Java?
Write a method to shufle the deck. The constraint is it has to be a perfect shuffle - in other words, every 52! permutations of the deck has to be equally like (given a completely random function which is theoretical of course).
I managed to do this with a simple for loop in O(n) time
int[] deck = new int[52];
for(int i=0; i<52; i++)
deck[i] = i;
Random r = new Random();
for(int i=0; i<deck.length; i++) {
int ran = r.nextInt(deck.length-i) + i;
int temp = deck[i];
deck[i] = deck[ran];
deck[ran] = temp;
}
Design a Deck of Cards
Asked me the differnce between using Abstract class vs interface on a real world problem im working on (at one point he settled for an answer where is said "it's just intuitively wrong" - however, he tried to trick me into justifying using the wrong thing, I had to say that there is no justification for using this technique here, took a little bit of guts but he liked it)
Asked me to take some time around 1 hour and create an API that could read names,emp ID's,phone numbers, office names in that order from a file and stores them and has the following functionality:
1) getEmployeeById
2) getEmployeeByName
3) getEmployeesByName
4) editEmployeeInfoById
5) editEmployeeInfoByName
The questions were so easy, it was hard to tell if they were joking or if they had a trick up their sleeves.
Write simple state machine code in C
Remove a fixed character from a C-string
Asked about virtual functions, etc.
Wasn't asked anything nearly as challenging as I was expecting, yet they managed to create an environment to get me nervous enough to fumble some things regardless.
When contacted the 2nd recruiter, she told me the position might be filled but I can still interview in a week. A little akward.
Rate your C/C++/Java knowledge.
Describes interests relating to Citrix.
Have you ever led other people? Please describe the experience. What did you like and not like about it? What did you learn? (5 minutes)
Identify, in your opinion, three of the biggest problems plaguing the world today, and suggest a possible remedy for one of them. (8 minutes)
You have received a fantastic job offer and know that it is because your professor highly recommended you to the company. Below write a short thank you note to her/him. (Do not include the heading, i.e., Dear Professor X,). (8 minutes)
Describe a challenging experience you've had and what you did to overcome it. (5 minutes)
A friendly alien from a distant galaxy is visiting Earth. It wants to know how to greet a dog. How would you instruct the alien to approach a dog and express affection? The alien can see and hear you, but it cannot understand your language. (10 minutes)
What is one of your favorite meals or snacks to prepare, and how do you make it? (3 minutes)
You really want to attend Hudson University in New York. It is your first time visiting an American university, and you do not want to apply without seeing a dorm room. However, the security guard at the front desk tells you that you need a Hudson University Student ID to enter the building, no exceptions! How would you get into the building? | Come up with at least two strategies. You may not offer her money or any other favors, and you do not just happen to have a fake ID with you. (7 minutes)
Please list the most important technology hubs (by city area) for:
(at least 5 each)
Asia
Europe
Americas
(6 minutes)
The purpose of this interview is to evaluate your written communication skills. I will ask you a question every few minutes; before I ask the question, I will let you know exactly how many minutes you will have to answer. I will keep track of the time, and I will prompt you for a response if you haven't provided one already. I am going to ask you a total of 9 questions. The whole evaluation will take no more than an hour. Whenever your box fills up with a part of your response while you're typing, just send that part in and then continue typing the rest.
kanariay: Your response to each question should be at least 4-6 sentences. Please answer the questions in complete sentences to the best of your ability. Don't worry about making mistakes - I am aware that your answers may be less polished than if you had more time to revise your grammar. Feel free to be creative - there are no right or wrong answers. Are you clear on how the interview will work?
Pretend you are writing a letter to your university to complain about an unfair professor. Write the first paragraph of this letter. (This time, include the heading.) (8 minutes)
Giving Two Strings, Find out whether they are Anagrams or not?
Define Test Cases for this Anagram Checking Function.
You are short of time and you have to do testing, What will be your strategy?
Given a deck of nCards unique cards, cut the deck iCut cards from top and perform a perfect shuffle. A perfect shuffle begins by putting down the bottom card from the top portion of the deck followed by the bottom card from the bottom portion of the deck followed by the next card from the top portion, etc., alternating cards until one portion is used up. The remaining cards go on top. The problem is to find the number of perfect shuffles required to return the deck to its original order. Your function should be declared as:
static long shuffles(int nCards,int iCut);
Mailed me this code and asked to find the mistakes in the code
class Base {
public:
Base(int numElements) {
m_baseArray = new int[numElements];
}
~Base { //non-virtual
delete [] m_baseArray;
}
private:
int* m_baseArray;
}
class Derived : public Base {
public:
Derived(int numElements) : Base(numElements) {
m_derivedArray = new int[numElements];
}
~Derived() {
delete[] m_derivedArray;
}
private:
int* m_derivedArray;
}
int main(int argc, char** argv) {
Base* base = new Derived(3);
delete base;
return 0;
}
What is wrong with the code ?
Given two dates, Design an algorithm to return whether the dates are exactly a month apart, less than a month apart or more than a month apart.
What is Polymorphism, how do virtual functions work
Print out a multiplication table, i wasnt told what kind of data structure it is, just that it has 1*1=1, 1*2=2, ...... 200*200=40000, ..... values.
When would a program crash in a buffer overrun case. Gave me,
buff[50];
for( int i=0; i <100; i++ )
buff[i] = 0;
What will happen to first 50 bytes assigned, when would the program crash
Imagine you have an unbalanced binary search tree. Design an algorithm which creates a linked list of all the nodes at each depth (eg, if you have a tree with depth D, you'll have D linked lists).
Each node in the linked list should have previous/next pointers (for the linked list) and left/right pointers (from the tree). Code this algorithm and then test it.
3) How will you remove duplicates from a sorted array?
Q) Find as many solutions as you can to remove a duplicate integer from an unordered set of integers from 1 to 100.
Write code to remove duplicates from an *unsorted* linked list. Let's say a temporary buffer is not allowed. Find as many solutions as possible. Can you do better than the O(n^2) solution? Construct test cases.
Q) Lets say you have a disk of size N with N blocks. Every block stores part of a file. Every file starts from a single block.
The block size is not enough to store a file. Every block has a used/unused bit and a pointer to the next block in the disk which will store the next part of the file
and so on. A block which stores the end of a file points to null. Also a block whose unused bit is 0 doesnt point to anything and is not pointed to by any block.
Now u have an index of files with filename as index and the value as the first block in which the file starts.Lets says u somehow lose these indices and values.
How will you find an efficient algorithm to recreate this index structure with values. You can use any filenames while creating the indices.
(While solving one shld think of cases where the file starts at block 4 which points to 1 then to 2 and ends at 3)
Q) Test a fibnoacci series program for undefined integer sizes without using a integers maximum size in the program.
Write a program to detect if a number is a palindrome
Gave me a piece of code...which is as follows...
Class A
{
int x;
}
Class B
{
int y;
}
Class C : public A, B
{
int z;
}
A *aa;
B *bb;
C cc;
aa = &c;
bb = &c;
Tell me do aa and bb point to the same address? If yes or no....why?
What is the difference between application interface and programming interface?
Interviewer> How many round trips happen during server.transfer and response.redirect?
Interviewer> If we have a table containing Emp_ID,Emp_Name and Dept_ID(Primary key) and another table having Emp_Name and Dept_ID (foreign key), how would u find the number of employees in each dept?
Interviewer> Assume if page1.aspx has response.write("Hello") and does server.transfer to 'page2.aspx' and page2.aspx has response.write("hello1") and does server.transfer to 'page3.aspx, then what do page3.aspx display? (does it display information in Page3.aspx page only or everything that Page1.aspx and Page2.aspx displayed? Why?
Interviewer> Which member function of Sqldataadapter is used to fill the dataSet?
Interviewer> How to find the number of records in a DataSet?
Interviewer> What's the difference between DataView and DataReader?
Interviewer> If we have to validate 2 testbox in ASP.NET using JavaScript...how to do u it?
Interviewer> difference between Server.Transfer, Server.Execute and Response.redirect?
Interviewer> What GroupBy in SQL do?
Interviewer> How to find the number of records in a DataReader?
Interviewer told me a good amount of their code is inefficient or hard to maintain. Hence, the position.
Describe experience improving software.
A couple questions he responded, "I'm not the person to answer that."
Describe experience with Web Apps.
Describe courses taken.
void type pointer, pointer arithmetic
one person can finish painting a house in 6 days, another in 4 days. if they work together, how long would it take to finish painting?
data structures: to sort some elements, what data structure would u choose? would u choose hashtable, why not? blahblah
How would you implement C++ in C?
given char arr[100]. what is strlen(arr) and what would printf("%s", arr) do?
Describe experience with Unix and Unix scripting.
Describe experience with C++/Java.
What's the difference between Events calling delagates in C# and Pointer calling a function in C++?
Interviewer>What's a template?
My Answere>blah...the answere was not that impresive...he asked a million questions on that...what if this , what if that...i
don;t remember..
Interviewer>Does delegates have performance improvements or any advantages over functions calling in c++?
My Answere> ...No Idea ..
Interviewer> What's the differnce between C# and C++?
My Answere> C# code does not require header files..C# does not have multiple inheritance...
If a variable is a Global Variable, then where it's stored in memory?
Interviewer>Assume that we have a string being passed to a function with a char pointer, write a pgm to reverse the string?
My Answere> blah...blah..
Interviewer>What is a stack? What operation does it do? (Well he asked me this question b'cos i answered the variables are
stored in Stack)
My Answere> Stack is a storage location with push and pop operations..
Interviewer>If there are variable defined where the variable stored in the memory?
My Answere> All temporary variable are stored in Stack.
Interviewer>How would u intialize a pointer?
My Answere>new and malloc
Interviewer> What is a event and how is it related with delegates?
My Answere> Blah....blah..
Interviewer> What was the most challenging project ever done? Why?
My Answere> Blah...Blah... (We discussed for nearly 10 Mins...these guys know we are talking abt)
Interviewer>Let us assume there is variable size (size cannot be determined) of string data coming over a network how will u
declare a char to display the string?
My Answere>Would use a pointer char rather than a fixed char like "char a[50];"..
Interviewer>What is the syntax for mallac?
My Answere>blah..blah..
Interviewer>Assuming that 5000 bytes of string data is in buffer, how would u define the pointer?
My Answere>Dynamic allocation...blah...blah..
Interviewer>How do u copy the reversed string into another variable i.e. if we have 'hello' the other variable should have
'olleh'?
My Answere>Well I just gave an idea on how to get it woking and he bombared me with questions such as "how can determine the
size of the pointer...give a C implementation not C++!!"
Interviewer> What is a delegate in C#?
My Answere> They are reference types which performs indirect calls to methods ...blah...
Interviewer> What's the differnce between C# and Java?
My Answere> C# can overload operators but Java cannot and Java is platform independent and C# is not.
Interviewer> Since STACK does push and pop, so what if the stack pop's the Global variable?
My Answere> Variables are poped only if it's out of scope..
(My answere was wrong....he said that the Global variables are not stored in Stack!!)
Explain how to write a stored procedure in SQL
Design an algorithm and write code to serialize and deserialize a binary tree/graph
Phone Screen 2: Check whether the bit representation of integer is a palindrome
Multithreading and operating system stuff
What would you do with an object that is used as a key to a hash data structure?
Difference b/w interface and abstract class?
Describe polymorphism.
Difference b/w shallow & deep copy?
What are the trade-offs in C++ vs Java?
Describe technical experience.
Received phone-call from recruiter. Described the position to me and arranged a phone interview.
E-mail reply from chief architect. Told me they weren't satisfied with my answers.
Constantly repeated that I wasn't articulate about my solutions.
Suppose that you have access to a file which contains the closing price for 10,000 stock tickers on each day over a period of 10 years. Suppose also that you must create a component of a computer program which will be called thousands to hundreds of thousands of times per day on many different days to:
(A) Retrieve the closing price associated with a given stock ticker for a given date.
(B) Iterate through all stock tickers that have price information available on a given date. (C) Find the last date before a given date for which a given stock ticker had closing price information available. What data structures would you use to organize this stock information to best satisfy (A), (B) and (C)?
I mentioned BST & Hashtable.
Assuming that you could play this game as many times as you liked, how would you decide how many times to play it? NOTE: Though question 2 is central to much of human activity, there is no single agreed upon solution to it. We are interested in the reasoning that you undergo to arrive at a reasonable conclusion
Consider a purely probabilistic game with potential outcomes x1, x2, ..., xn (each of which is a specified gain or loss of some number of dollars) which occur with the probabilities p1, p2, ..., pn respectively (where, p1 + p2 + ... + pn = 1.0). Assume that x1, x2, ..., xn and p1, p2, ..., pn are known. Theoretically speaking, how would you define or measure the risk of playing this game?
Explain why you believe that the data structures you chose are the best ones for this job.
Would you load all the stock information into memory at once, or format the data before hand so that it could be read piece by piece from the hard drive as information is requested?
Assuming that you could play this game at most one time, how would you decide whether you would want to play it?
Recruiter told me CME will extend an offer.
Basically told me what they need and how comfortable I am with completing that assignment.
lots of questions straight from programming interviews exposed
a) detecting loops in a linked list
b) Different ways to find the no. of set bits in an integer(bitwise operators).
General questions about linked lists, binary trees, arrays, heaps ...advantages, disadvantages, complexties, differences between each.
Three ants on different vertices of a triangle. All can walk on the sides of the triangle. Find the probability of them colliding.(collision could be between any two or all three).
Now find the same for n vertex polygon with n ants.
Explain the following operating system concepts: virtual memory, context switching, semaphores etc
Write a function which uses malloc and returns a starting memory location which is a multiple of 32.
Any questions? I asked several questions.
What is static?
What is the difference b/w synchronized methods and synchronized sections?
What is the diff. b/w hashtable and hashmap?
Describe projects.
Describe how to ensure quality of a function.
Interview with Sys Analyst and Lead Prog. Analyst.
Suppose you have a 100 files in a directory and you need to find out if a keyword occurs in these files. How would you do it in Unix? How would you do it in Windows?
Suppose you have a list of jars to compile and some jars are dependent on others, what kind of data structure would you use to store the jar files? For example, if you had jars A, B, C, and D. A is dependent on B and C. B is dependent on D. What data structure would you use to store these dependencies? Which jar would you build first? B or C?
There were some general questions about my current job. Windows or Unix/Linux? C/C++ or Java? And common questions like those.
How would you handle the above situation if say you had 10 million files?
I was just asked 1 question. How would I find common elements in two arrays and discard duplicate results. I said sort the arrays as binary trees so that is o(n lg n) and while sorting remove duplicates. Now searching will take lg n. I guess this was not the best answer.
Given a dictionary of millions of words, write a program to find the largest possible rectangle of letters such that every row forms a word (reading left to right) and every column forms a word (reading top to bottom).
Anyone got any ideas?
reverse double link (improve the algorithm with no additional memory, no redundant computation)
Given a directed graph with multiple nodes, design an algorithm to find out whether there is a route between node_a to node_b
Write a class with static/non-static data member, static/non-static/virtual, draw the object model
Write a method to compute all permutations of a string. You can do this either recursively or non-recursive
I asked most of the questions: group vacations, work schedule, environment, etc.
Describe experience w/ mult-tier architectures.
Describe experience w/ stand-alone/enterprise Java.
find dup number for n+1 numbers from 1...n
Sent a 150 MB portfolio. Received offer shortly after.
to find a telephone number in dir and subdir (find command is the answer)
what you don't like in a job
What are you looking for in a job?
no.of 1 bits in a number ---program
database question like self joint with tables given by him
Write code to reverse the words of a sentence and not the sentence itself eg:
Input: a quick brown fox
Output:a kciuq nworb xof
Test the code
Now what if there is a punctuation mark like a quick, brown fox ...we still want the output to be a kciuq, nworb xof and not a ,kciuq nworb xof
What if the developer did not want to fix this bug since it is not there in the specs...what would you do?
Write code to delete a node from a linked list. Write test cases for the code you have written
Hands on testing: test msn entertainment web page
More behavorial questions and situational questions
You have a singly linked list say 1->2->3->4->5 and you have no access to its head pointer. But you have access to another pointer which points to the node 3. How would you delete node 3 and get the output at 1->2->4->5. Remember its a singly linked list
Construct a singly linked list tail to head
What groups would you like to work for?
Design an interface for a multimedia library
Insert a node in a doubly linked list
What is multi-threading? What are the things you need to worry about when using it?
Construct a singly linked list head to tail
Write code to reverse a singly linked list
Construct a Binary tree in which each node has n children
Describe projects outside of academics.
Describe what you like to do.
Q8.Write a function that will return the 5th element from the tail of a singly linked list and explain how you would test your solution.
Q6.What is a static property? Give an example of why you would use one.
Q2.What is the difference between an Interface and an Abstract Class (e.g., between IFoo and Foo?)
// Interface
interface IFoo
{
void Bar();
}
// Abstract Class
abstract class Foo
{
abstract public void Bar();
}
Q4.Describe how a try..catch..finally construct works.
Q3.How do you embed a special character (e.g., ‘{‘ ) inside a String.Format format string? Please give an example.
Q5.What is the StringBuilder class and why would you use it?
Q9.Write code to implement a class for wrapping text stored in a file. You should add enough functionality to the class to demonstrate your ability to design classes with either the C++ or C# language.
The class should at least meet the following requirements:
1.The class should be named CPersistentString
2.A class instance should flush its string to a file before it dies.
3.The class should support at least the following operators: "=", "==", and "[ ]".
4.The class should include the following operations: GetLength(), IsPalindrome(),Load(), Persist().
Q7.What are some of the potential pitfalls of boxing and unboxing?
Q7. What are some of the potential pitfalls of boxing and unboxing?
Q5. What is the StringBuilder class and why would you use it?
Feel free to add more than just the minimum requirements. You may use any functions in the standard C library (for C++) or .NET framework (for C#) and you may use a compiler to check your work.
What is a static property? Give an example of why you would use one.
Q4. Describe how a try..catch..finally construct works.
Q3. How do you embed a special character (e.g., ‘{‘ ) inside a String.Format format string? Please give an example.
Q9. Write code to implement a class for wrapping text stored in a file. You should add enough functionality to the class to demonstrate your ability to design classes with either the C++ or C# language.
The class should at least meet the following requirements:
1. The class should be named CPersistentString
2. A class instance should flush its string to a file before it dies.
3. The class should support at least the following operators: "=", "==", and "[ ]".
4. The class should include the following operations: GetLength(), IsPalindrome(),Load(), Persist().
Feel free to add more than just the minimum requirements. You may use any functions in the standard C library (for C++) or .NET framework (for C#) and you may use a compiler to check your work.
Q2. What is the difference between an Interface and an Abstract Class (e.g., between IFoo and Foo?)
// Interface
interface IFoo
{
void Bar();
}
// Abstract Class
abstract class Foo
{
abstract public void Bar();
}
Mostly behavorial questions on work/technical experience.
Asked me what I did with SQL. What DBs I've worked with.
Demoed some of their work involving FileMaker.
Asked to describe an OO Design for a card game. Most of the 2nd interview was about OO Design and trade-offs in that design. Questions like, if the manager came in and said add a border to an existing GUI, how would you approach that?
1st interview with online developer. Told me to describe my work experience and technical experience.
Describe psuedo code to count the number of 1's in a binary number.
Describe a project you've done. (be passionate)
Give an algorithm to find the convex hull.
Why do you want to be a SDET? (you need a strong answer for this. it'll be asked a LOT)
Given a tree such that each node has a child and sibling, find a node in the tree.
Prioritize the search by level (ie., check all siblings before children).
Hint: use a queue
Test a bottle of soysauce.
Hint: Test these categories:
Accessibility - accessibility, platform
Robust - stress, load
Operation - acceptance, performance, boundary
Security - security/safety
Two robots are each standing on a beacon, on a line of infinite length.
They both execute the same code. Write the code to have them collide.
Only use these commands:
SKIPNB - skip the next line of code if not on a beacon
MVR - move right one step
MVL - movel eft one step
JMP - goto label in the code
hint: have both robots move to the right in a loop. if a robot passes a beacon, double its speed.
Given a consecutive list of numbers from a to b, one number is removed.
The list is then scrambled. Find the missing number.
int find(int a, int b, int *array);
hint: sum(1 to n) is n(n+1)/2
using the same logic, sum(a to b) is (b-a)/2 * (b+a)
Write code to find the dot product and cross product.
Given 3 points on plane and a point in space, find the distance between the point and the plane.
Find the location of the point projected to the plane.
Test this function: void setTime(LPFunc func, Time t);
func is a functionpointer which will be invoked, passing in t as a parameter.
Given a chunk of memory
1. Implement malloc.
2. Implement free.
Add numbers in base n
A disk is partioned into two hemispheres colored in black and white and the disk is rotating.By appropriate positioning of sensors (A sensor can read the disk near it as black or white) we need to find the direction of the motion of the disk.
Mostly behavorial questions dealing with experience.
Asked about my experience with middle-tier development.
What is an abstract function?
What is the difference between copy by value and copy by reference?
How does binary search work? What is its complexity?
What is a good object oriented design?
What is an ideal data structure to traverse through in order to create a depth-first spanning forrest?
What is polymorphism?
What is the difference between an object and a class?
What would you do if you were given a project and couldn't finish it on time?
Write a program that traverses through a sentence and returns the words in reverse order.
Did I use JSP precompilation for one of my academic projects?
Describe a project
Why GS?
Why EA?
Describe pitfalls of C++ for a game engine.
Describe toughest technical challenge.
Why are templates in C++ useful?
Describe the debuggers you have used.
Write a function that sums & returns the digits of an unsigned integer.
What is your passion? I said the future and went into history(planes,Ford Model-T,etc.), quarks, and a vision of the future.
Told me to describe one of my personal projects.
Draw a basic ER diagram for Netflix.
Asked when and how I used UML.
I called the recruiter to get feedback. He told me 2 general reasons:
1. I didn't do my hwk and hence didn't know anything about VMware.
2. I mentioned tools from my personal project that weren't being used in the company.
Phone interview with senior engineer. Mostly behavorial questions such as "tell me about yourself." Told me to elaborate on a specific project and why I used the tools I've chosen.
Asked about virtual functions and function pointers?
Difference between reference and pointers? How can reference go bad?
Difference between malloc and new.
What is auto pointer in C++?
Some questions about STL? How can one store different type of objects in vectors or list?
What is reference in C++? Where will you the use it?
Here is a tree. It's a binary tree but in no particular order. How do you write this tree to a file so that it can be reread in an reconstructed exactly as shown?
What was your hardest techincal project?
Here is a graph of distribution centers and the weight to go from one to another. How would you represent this using a data structure? Code an alogrithm that allows me to check if there is a path from one node to another and what the weight of this path is.
Multiply a number by 7 without the * operator.
What was the most interesting thing you have ever done (technical or non technical) ?
I want to see if all the ones in a number appear on the right side of the number and all zeros appear on the left, how can I do this most efficiently? (i.e. 00000111 is true but 100010 is false)
Imagine you're implementing the game of chess. Design the classes, objects and heirachies behind it.
more architectural view about solve problem capability. I think the intervier was more realistic than the other two . Not just because he recommend to 2nd interview, since I also have the experience with recuriting other employees in the past. I felt the potenial is more than anything in work. Coding is just one thing , maybe the one who can solve the tricky algorithms is good in some way, but how about the one who has been out of school for several years and I cant remeber anything about mergesort or quicksort or how to find the shortest path blah blah. But I do have the confidence I am very good at work. No matter where I go, I found most people are not that smart and if you are willing to learn, you can be the best. Of course, you must have the potenial first. Like you are willing to learn and you like your job...
App server+DB server, solve the querying delay problem...
2nd phone interview: reverse linklist(so stupid, I was too focus on the rule using the exist library much better than build something new(Effctive Java) and when the intervier insisted on asking me to give the non extra memory consuming answer, I was stucked for a while then I told her to move on the next topic. Find the duplicate number from an array. I gave the hash solving method.but I also gave her other answers.
focus on my last project
MultiThread, Garbage Collection. Tomcat distribute request(Java Spaces), http protocal. Socket programming...
Write code to reverse vowels of string
Invited to on-site interview. All behavioral questions. Asked to describe what I wanted to do in GP and general thoughts on advancements in technology.
Given two log files, each with a billion usernames (each username appended to the log file), find the usernames existing in both documents in the most efficient manner? Use pseudo-code or code. If your code calls pre-existing library functions, create each library function from scratch.
The bigger the ratio between the size of the hash table and the number of data elements, the less chance there is for collision. What is a drawback to making the hash table big enough so the chances of collision is ignorable?
How could a linked list and a hash table be combined to allow someone to run through the list from item to item while still maintaining the ability to access an individual element in O(1) time?
1st interview continued: e asked a few more technical questions on interfaces vs. abstract and do you really need a VTBL in Java all the time since virtual functions are implied? I refered to a Use Case diagram to explain why interfaces are important. Also asked some basic questions on Java like what is a final class, abstract class? Asked to describe my experience.
ow do you find the size of something in C? Why does sizeof exist in C/C++ and not in Java?
2nd interview was on-site, with one of the team developers. Given a linked list, swap values inside nodes. Now do it by swaping the node pointers. This wasn't a hard question at all, but more of an organization question for me because it was kind of a twisted question and easy to be off by one pointer.
3rd interview was with some other developer. Given two arrays of signed integers. Find the intersecting set of the two. Describe different solutions. He once exclaimed that I was digging into the next question and said I was the only one so far to do that. The next question was implement strpbrk(char* str,char* find). It should return the string starting from the first character matched(find contains a string of characters). We ran out of time as he was asking me how to optimize my lookup(I was using an array).
4th interview was w/ the tech lead. Asked a puzzle question and told me to use a recursive algorithm. A grasshopper wants to cross a river onto the other side. Partition the length he was to cross into intervals. Each interval either has a at most 1 stone or none. The grasshopper has to jump on the stones to cross the river. It has a speed which is the number of intervals/jump. Initially speed is 0. To get to the 1st stone, speed has to be 1. Given a boolean river array telling if an interval has a stone, call another recursive function to see if it's possible for the grasshopper to cross the river. Speed can only be decreased by one, same, or increased by one. Didn't fully complete this function but he told me I was awefully close.
What features would you incorporate into the hotel functionality of expedia?
Asked a couple of questions about sorting algorithms, time and space complexity.
Asked a few questions about my current research.
Questions on topics related to the projects on my resume.
Was given C code for Base64 Encoding & asked to identify bugs in it.
Algorithm: You have a tree (not Binary) and you want to print the values of all the nodes in this tree level by level. Discussed on phone and asked me to email Java code for my algorithm.
Unix: You want to kill a process that has been running for a long time, how to do that?
Unix: You have 50,000 html files in a UNIX directory structure, some of which contain phone numbers in the format ***-***-****. How would you create a list of all the files which contain phone numbers? (Assume that you already have the regular expression)
XML: Differentiate between SAX and DOM.
Data Structures: Time complexities for HashTable, Linked List, Binary Search, Array.
Java: Differentiate between final, finally and finalize
XML: How have you used XML in your previous projects?
Java: How does the synchronized keyword work? What happens when you use it on a static method?
Java: Talk to me about the Java Collections API
What's wrong with this code:
unsigned int i;
for (i = 100; i >= 0; --i)
printf("%d\n",i);
Count the number of ON bits in an integer.
Write atoi(const char * chr)
Describe in english what this code do?
( (n & (n-1)) == 0)
What does the keyword volatile mean in C?
Describe in English what this code does:
((n & (n-1)) == 0)
Explain Virtual Memory. What is the TLB?
Design Patterns - Talked about Singleton, Observer, Abstract Factory.. more
Asked about Java OOP.
What do you do if a member of a team does not work as hard as the others?
Software Architect: Tell me about your projects?
Write an object(class), called StockCache, that caches a single stock every couple of minutes. What are the function prototypes? Where would you need to put in thread protection? How would you organize the set of StockCache objects?
CTO: Tell me what kind of position you are looking for?
Software Architect: He went over the quiz/test that I had done and asked me a couple of questions on how I could improve certain algorithms, add thread protection, etc.
CTO: What is your favorite project? Project challenges? What is your leadership style?
The same test as Gayle's. But they may change that test (according to one of the manager's) but expect similar questions.
Determine if a string is a palindrome. (Remember to think about spaces and capital letters).
Describe a project you worked on... He wanted me to draw the whole thing out on paper in graphical form.
What are some of the challenges you have faced when working with a team?
Determine is a graph is circular.
Given an array of integers where every int has exactly one duplicate except one,
find the number with odd occuring number.
assume your computer is reading characters one by one from a stream (you don't know the length of the stream before ending). Note that you have only one character of storage space (so you cann't save the characters you've read to a something like a strong). When you've finished reading you should return a character out of the stream with equal probability.
For your past projects, which design patterns did you use? Why those ones and not others?
How would you load test a web page without using any test tools
Given two binary trees, find whether or not they are similar.
Remove characters from a string. What is the running time of your algorithm? Can you do better?
Everything I said they responded "Are you sure?", "Are you sure about that?"
While writing the code, they would question it and laugh, trying to trip you up, even when you were right. Supposedly to see how you handle under pressure I guess.
These guys thought they were the best thing ever because they got paid bank and lived in Manhattan. (But they live in Manhattan so it's not really as much as you'd think...)
Sort of lame questions like:
What will this do? int main(){
return main;
}
How much memory will it use each call? (Depends on compiler optimization or not)
Stress interview. They would interrupt each other and force me to answer questions that the other one had interrupted me on.
Design a hash table to store phone #s. Your job is to write a hash function that has a parameter username, and generate a key. Username is unique, length 5 and can be A-Z, 0-9, space. Write a hash function that generate keys without collisions and use minimum memory.
Count characters in a string, wanted to see a hashtable used.
Write in java a method to parse an integer from a string
count bits in an integer. Solved using mask, did not attempt -1 approach.
Reverse a linked list
How can you rate C++ and Java out of 10??
Please write a function to reverse the Linked List in the language that you are comfortable with.
If you are hired, where do you stand after 2-3 years?? Do you have any goals to achieve??
How can you improve your test case, tell me the test case in best time and space complexity.
Tell me about one of the best challenging projects that you have done?? Also tell me about the critical situation that you came accross technically and how did you fix it??
Please list the cases to test your function.
Please tell me about your college background and about yourself?
Why do you want to work at Microsoft, How can you say Microsoft as your best place to work, and basically WHY MICROSOFT???
What is deep copy in C++ ? When would you use it ?
You will use deep copy when you have dynamically allocated members in a class. Do not forget to mention that you need a corresponding destructor to deallocate.
Please refer to
http://groups.google.com/group/ cse-interview-questions/browse_frm/thread/1e31c59a3580e236/9a6d297742c32463?q=deep&rnum=1#9a6d297742c32463 page for more info.
Puzzle: You've got an 8×8 checkerboard and a bunch of dominoes that each fit nicely on two squares of the checkboard. You can easily tile the entire checkerboard with these dominoes. Now say that you remove two squares, one at one corner and the other at the opposite corner. You're left with 62 squares. Can you tile this with the dominoes? If so, show how. If not, prove why not.
Is FORTRAN pass by value or pass by reference.
Ans: parameter in FORTRAN are passed by reference
What did you use to connect perl to database ?
What is the command in perl to remove leading and trailing whitespace ?
Ans: Chomp
Gave the code for reversing a linked list. Asked me to identify all the bugs.
Gave me some C code for a compression algorithm. Identify bugs.
Why do I want to work for Bloomberg?
Asked me about XML. XML was on my resume but I don't know much about it. I only have used it a few times. Note to self - take anything that I don't know too well about off my resume.
Asked about unix commands
What's the difference between malloc and calloc? What's static methtod in C?
Describe a binary tree, its properties, and name all of its traversal algorithms.
Discussed OOP concepts and gave examples.
What is difference between Java and C++.
What's the difference between Linked List and ArrayList?
Why is Virtual Memory important?
Asked me basic unix commands (wc, grep, ls, ps, top, find) and which unix text editor I use.
Implement a Garbage Collector for C++.
How does the compiler know which virtual table to point to when the base class pointer points to its derided class object?
What is an array? What is a Linked List, Map.
Why do you want to work here?
Complexity of insertion and deletion for linked list.
You have eight balls: seven are the same weight, and one is heavier than the rest. Given a scale that only tells you which side is heavier, how do you find the heavy ball?
Favorite feature on Amazon personalization site
How did you hear about Amazon?
Given 3 files, each with names of thousands of customers who bought something from Amazon.com on that particular day. Find the common customers (i.e. common names in file1 and file2 and file3)
Print BST level by level
Given 2 files, each with names of thousands of customers who bought something from Amazon.com on that particular day. Find the common customers (i.e. common names in file1 and file2)
How would you test an ATM in a distributed banking system.
Check if binary representation of an int is a palindrome or not.
What's XD bit? How does buffer overflow work?
Computer Architecture: Virtual Memory, Interrupts, Cache, Hazards, CISC vs RISC.
When do you use a double pointer?
Draw all the components of a computer!
Behavior questions: favorite internship, projects...
Design an algorithm to find duplicates in an array. Discuss different approaches.
Design an algorithm and write code to find nth node from the end in a linked list
Design an algorithm and write code to shuffle a standard deck of cards
Design an algorithm and write code to serialize a binary tree. Discuss various solutions
exception handling, C++ basics, bitwise operations
Background - what do you do? what positions interest you etc?
how do you go about deciding what to automate or not?
given a string - separate out the words of the string. put the words in a DS of your choice?
What advantage would you get with a linked list over an array in this case?
Given a binary tree, write code to check whether it is a binary search tree or not
Suppose there is a problem with the address change feature on Amazon.com. How would you test it? What data sets would you test it against? How would you decide on such a data set?
Do you have unix experience? Have you heard of WC (word count). Code it in c/c++. You can use STL.
Suppose you are in charge of the login feature for Amazon. How would you test it?
the "logging in" feature of amazon.com has a problem. isolate the problem.
asked some questions based on my previous job
Lunch - QA manager.
1. tell me a situation when u had to face problems and the requirements were not clear. how did u handle the situation?
2. which is the best error you have caught?
3. which is the worst error u've ever caught?
4. asked about a project on my resume
You are given an array of length 99 that contains all the numbers between 1 and 100, except for one number that has been removed. Find the missing element.
Suppose you have a calculator service running on a server. Automate the process of testing it. (i.e. you should be able to fully test it by just clicking a button saying "test").
What if you didn't have access to the input and expected output? For example, you have no excel sheet that has the expected values. Generate the 2 inputs on the fly - how would you automate the testing?
write push and pop for stack
say i give you a universal vegetable cutter which claims that it can cut any kind of vegetable. TEST IT.
What programs have to be running on the server and client for an NFS mount to work (answer: to work, just nfsd and mountd on the server; although both client and server SHOULD be running nfsd and mountd)
Asked me about projects on my resume. To the minutest detail possible.
Asked me to test an API they had developed. It was by the test lead. Coincidentally I gave him the exact test cases that he had come up with :).
Write a function to merge two sorted linked list in a sorted order. Test it.
Write a function to use up a user given percentage of free memory in a system. Had to optimise for performance. Write test cases for the above. I could assume any suitable API that was there. By the way it was for an embedded chip.
Asked me to write all code for design and implementation for my idea of the C++ string class. Wrote code for about 1hr 15 mins. Then he was satisified and asked me to stop.
Asked me to write a couple of functions. One took a function pointer, checked the process Id of the calling process. Check if the process was alive at specific intervals, if yes then invoke the function (pointed by the FP) otherwise return.
Second function would take a request from the process to stop the first function. Was asked to design my own data structure and had to show it works with large no of processes. Had to write test cases for it.
Write code to delete a node from a binary tree.
What is an algorithm to balance it?
Write the code to find the inorder successor, if each node has a link to its parent.
Copy a Linked List, and delete all even data from the Linked List.
2nd inteview was with Team Leader. He intoduced the group to me and the work they do. Then asked me lots of COM related questions. Platform Invoking. Calling unmanaged code from managed code. Why would one want to use COM against C# and vice versa.
Design a graph class. Write the C++ interface for it.
Write a function to smooth out stock fluctuations. Asked me to layout the mathematical idea for curve smoothing before writing code.
Say you have a system. The design is good. But performance is not good. How would you find where the problem is? went on for about half an hour about it.
Write a function to find the no of set bits of an integer. Optimise. Ended up giving two solutions . Could not implement the third one.
Given two sets, Write a function to provide the union of them. STL not allowed to be used.
Optimise for Time and space.
Design an algorithm to calculate the most user viewed pages
How do I go about motivating my team?
Why do I want to work for JP Morgain and Various typical behavioral questions.
Asked me about OS projects.
Why do I want to study Computer Science?
Asked what I do on my free time? I said Yoga. He wants me to sell him yoga.
Asked me my knowledge of J2EE.
What are some languages that you're proficient at?
What did you learn on your previous internships.
How do you go about learning a new language?
Tell me about yourself, your coursework.
Your favorite class and professor.
Case Study: The IRS wants your team to build an application to do taxes. Write the initial proposal. Design and architect your solutions. You got to discuss this in details.
What are some advantages and disadvantages of building your software on top of open source projects?
What kind of project are you interested in?
1st Interview - Mainly behavioral questions and experiences
3rd Interview - Technical. You have 5 basketball teams. You want them to play each other only once. Each team plays once a week. If a team plays a home game this week, They should play a aways game the coming week. How many weeks does it take for all the teams for play each other?
Behavoiral questions: Leadership skills. How did you convince your to accept your ideas? Conflict resolutions.
Asked about Stack, Stack Frames, Heap, variable allocations and destructions.
Asked about Interrupts and exceptions.
Talked about Garbage Collector. Explained Mark & Sweep Algorithm.
Where do you see youself in 5 years?
Tell me a time where you showed your leadership skills
A time where you showed initiative.
How do you keep your team motivated?
Your hardest class.
Behavorial questions. How do you motivate your team? How do you tell a co-worker that he/she aren't doing a good job.
Differences between process and thread
what are core dumps? What kind of editor do you use to look at core dumps?
virtual and pure virtual functions. Virtual inheritance.
Basic data structures questions. Linked List, Arrays, Splay Tres, Binary Tree, Hash. Discuss when you should use Hashing over Tress.
Questions about Linkers and Loaders.
Questions about OOP, Design Patterns, Java, and C++. Just basic OOP questions like Pure Virtual Functions, Virtual Pointer Table, Abstract classes, Interfacce, Inheritance, Polymorphism.
Questions about past experience. Teamwork and leadership skills.
What is a dot product and cross product? What do you use them for?
What games do you play?
What type of courses do you find the most difficult and why?
What was your hardest course?
What's 2^10?
What will be the next breakthrough in gaming technology?
Tell me about a project.
What is a hash and what would you use it for?
How would you detect a repeated element in an integer array. Discuss various solutions and the order of the algorithm.
What is a Pure Function?
Why do you want to work at Amazon?
Talk about your favourite project? What part of a Software Project do you enjoy most?
Tell me about your work experiences in the past?
3. What is black box testing?
4. What do you include in a test plan?
You have a website which has 5 reads on a database when it is loaded. Each read takes 7 seconds for a total of 35 seconds, discuss how you could improve the performance?
What is a linked list? What are its advantages over arrays?
What's the difference between a process and a thread?
What is smart-pointer in C++
100 closed lockers. You begin by opening all 100 lockers. Next, you close every second locker. Then you go to every third locker and close it if it is open or open it if it is closed (call this toggling the locker). After your 100th pass of the hallway, in which you toggle only locker number 100, how many lockers are open?
You have an array of strings. How would you sort the strings so that all the anagrams are each other?
What are all the thing things would you need to consider while designing a vending machine?
How would you represent a game of tic tac toe (data structures, etc.)? Improve on the design. Implement it in pseudocode.
If you have existing list linked list, and you are given a new one... make as few updates as possible to transform the old list into the new one.
Develop a way to represent 32 bit numbers as 8-character strings (including the null character, so 7 bits of data). You can use 0-9 and a-z. Code it on the board. Develop unit test cases to test your code.
Asked me to go through all of my summers at Microsoft and Apple and explain what I did
How would I compare Apple and Microsoft
Explain a technical project in a non-technical way
Asked me what the lead student ambassador position is and what I've done with it
You have two ropes, each of which burns for exactly one hour. But, the ropes vary in density so you don't know that half of one rope will burn for 30 minutes. Given those two ropes and a book of matches, how would you time 15 minutes? (Note: you don't need to be able to hand someone a piece of rope that will take 15 minutes. You just need to be able to time 15 minutes)
A bunch of couples are on an island. A genie comes down and gathers the men together and tells them: "I know for a fact that at least one of your wives is cheating on you. So, if your wife is cheating on you, I'm going to put a code on your head." The men then ask for a way to remove it, which she grants: "to remove it, you must dunk your wife under water at exactly midnight. If you are wrong, you die - so don't mess up. You will not be able to see or feel the crown on your head, but everyone else can. However, they are forbidden to tell you or signal in any way that you have a crown." How long does it take the men remove the crowns? (Assume there are n men and c crowns. The men do not know what c is)
You've got a 5 quart jug and 3 quart jug, and an unlimited supply of water (but no measuring cups), how would you come up with exactly one gallon of water?
Test: Imagine that you're writing an email spider-er... What would you do to test it?
Test: How would you test an email client? What could be automated? What wouldn't make sense to be automated?
Test: How would you test program to generate first n random numbers
Algorithm: Describe an algorithm to determine if a singly linked list is corrupt
Algorithm: Give the most efficient algorithm to determine if a string has all unique characters
Coding: Write program to continuously keep average. ie, you have a prototype function "double computeAverage(double newVal)"
Coding: Write a program to determine if a binary tree is well ordered
Coding: Write a program to swap a number in place (ie, no temp variables)
Coding: Write atoi
Coding: Write program to reverse a string
Coding: Write program to take the union of two rectangles
If you were an absentee landlord, how would you take care of your housing?
Design a key fab targeted at a 16 year old girl whose father is buying the car
Assuming price is no object, what would you put in a handicapped bathroom?
Design: How would you design an ATM for the blind
What's your favorite Microsoft product? Name five ways you could improve it
Explain Object oriented to your grandmother
Explain webservices to your grandmother
What's the next big invention?
Explain Object Oriented Programming to your grandmother
What area of life is left for technology?
Name 5 programs that you think could help in retail
- What technologies would you use?
Code: You have an array of integers (both positive and negative). Find the continuous sequence with the largest sum. (ie, if the array was {6,-8, 3, -2, 4} then you'd want to return {3,-2, 4})
Code: print a linked list in reverse order
- Can you do this in O(n) time, O(1) memory? [O(1) memory = no recursion]
Implement shoot(x,y) in the game of battleship. What are the data structure you would use? What are the algorithms?
Code: Find the first occurence of a string in a multi-string. (multi-string means that you could have a string like "cat\0dog\0monkey\0\0". The true end of the series of strings occurs when you hit two null chars in a row)
Code: You have two sorted integer arrays and the larger array has room for the second. Merge the smaller array into the larger one, in O(n) time and O(1) space.
Code: Reverse C-Style String. (C-String means that "abcd\n" is actually represented as six characters")
Design a remote control for blinds in an upscale home. Design it to control multiple blinds. Is it easy enough for your grandmother to use?
[Shown picture of climate control system for a car]. Redesign the climate control system for the next model year.
Imagine a bulldozer - thick tank tread, rotating cabin, extendable arm with claw on the end to pick up things. It is parked on the edge of a cliff. Fifty yards away a house is on fire. Lois Lane is on the third floor. Woody Allen is about to get into the bulldozer and rescue Lois Lane, and then speed after some bad guys in the bulldozer. Design the controls in the cabin so that there is a zero learning curve to figure out how to control all operations.
Pitch a new product to Bill Gates. Why should he invest it, how will it be profitable to the company?
What's the best designed technology?
What's the biggest mistake you ever made?
How would you design the interface of Project for CEOs?
Design: How would you implement scoreboards for different games played on Xbox Live?
- Databases, API, …
Coding: binary search tree:
- find element with given key and return
- node deletion
Coding/Algorithm: You know how web adresses convert spaces and such into special characters
i.e., space == %20
- given a string, convert the string to a string where all spaces are %20
- what are the different ways to do it
- what if unlimited memeory, what if you cant have any memory and the string has extra space at the end that isnt used (buffer)
- what if you want to say if the string will cutoff and only convert if cut off
Coding: You have a linked list
struct node
{
int selected;
struct node *next;
struct node *child;
}
intitially all childs are null and it is just a linked list
given a list with some marked and some not, make a linked list such that:
there is a linked list of just the not_selected, then the last element in that list is an element without any data but its child is pointing to a linked list that has all the selected nodes (the last element of which points back to the one with the child node)
- how would you traverse this new structure (even if there was a child that had other childs
- what if that circular connection was cut, then how would you traverse it?
- what if you can add a boolean value to the structure (that you can only set as you traverse). then how would you do it
Questions about prior project
Coding: 2 arrays, a and b, both are sorted ascendingly
you know the size of b
you dont know the size of a but you know a can at a minimum hold the size of the current valid values of a (all valid values are at beginning of array) plus the size of b
- How do you combine the two arrays into a while keeping a sorted when returned (no extra array to use)
Algorithm: You have a video card with memory. You can read and write to it. However, you can only write to it through a byte mask (if bit of byte mask ==1, then you can write to that bit, if == 0, the bit stays unchanged). Also, you can not read the byte mask (you can only change it). How do you determine what the value of the byte mask is (you can write to the video card as long as it is restored to the same condition as you left it).
Coding: Write code to compute the intersection of 2 rectangles
What's the difference between c++ and java?
Coding: Many overlapping rectangles - want to return which (doesn't matter which one, if it's over several) rectangle the mouse is over.
Coding: function generate nth fibonnaci number
- what's the largest n could be?
Coding: I have a HxW picture, 32 bit picture --> represented by int array. How do you rotate the picture by 90 degrees into a new array? Write the code
Coding: Reverse linked list
Coding: You have an n pointed star with points labeled 0, 1, ..., n-1 (assume points are numbered in order). You want to draw this star (imagine a kid's scribble for a 5-pointed star... That kind of star). Assume you have a function drawLine(int indexOne, int indexTwo) which can draw a line from one point of a star to another. Write a program to draw the star.
Coding/Algorithm: Since XML is very verbose, you are given a way of encoding it where each tag gets mapped to a predefined integer value. The language/grammar looks like:
Element --> Element Attr* END Element END [aka, encode the element tag, then its attributes, then tack on an END character, then encode its children, then another end tag]
Attr --> Tag Value [assume all values are strings]
END --> 01
Tag --> some predefined mapping to int
Value --> string value END
- Coding: Write code to encode xml element (as char *) as Byte *
- Algorithm: Is there anything else you could do to (in many cases) compress this even furthur?
Coding: Game of master mind: you have four balls, and four different colors, as a solution. The user tries to guess the solution. If they guess the right color for the right spot, it counts as a 'hit'. If it's the right color, but the wrong spot, it counts as a psuedo-hit. For example: if the solution is 'RGGB' and the user guesses 'YRGB' they have 2 hits and one pseudo hit. Write a program to, given a solution and a guess, calculate the number of hits and pseudo hits.
Coding/Test: I want to be able to maintain a list of my family's birthdates and print them in oldest-to-youngest order. Implement the classes and methods that I need for this
Test: how would you test this (if you were doing black box testing)?
Questions about experience at Apple
Algorithm: khanji has a LOT of characters in their alphabet and are using a way of compressing it so that the most common characters are 1 byte and the less common are 2 bytes. If it's a '1 byte' character, it starts with a 0, If it's a 2 byte character, it starts with a 1. If you're at a particular character (at the beginning), how do you find where the previous character begins?
What I did at apple
What is: in-order traversal of tree, quick sort in an array
What’s the difference between a vector and an array
Coding: return max depth of binary tree
- I used recursion
- How would you do it without recursion?
Difference between objective-c and c++
Coding: SQL query to select max value for each element (select max(salary) from Companies group by CompanyID)
Coding: SQL query to select number of elements in a table
On senior project, where did I use custom controls?
Algorithm: print a singly linked list in reverse order
Why I want to go to Goldman Sachs
Tell me about what you did at apple
What do you want to be in consulting
Tell me about something (course, etc) that was especially difficult (aka, what are your weaknesses)
Tell me about a team project - what was your role?
Tell me about a leadership position you've had - what was challenging about it?
Draw a entity-relationship diagram for a database with companies, people, and professionals (people who work for companies)
What part of the software development process do you like most
What type of team environment do you like to work in? How are you most effective?
Tell me about one of your projects
What did you learn from apple
What do you like to do in your spare time?
Please describe in detail your SQL Server experience over the last 2 years. Please describe in detail your tasks, projects, backup/restore, data feeds, replication, performance monitoring, upgrades, etc. What did you like to do best?
What did you learn from microsoft
Why kind of company are you looking for
If you were integrating a feed of end of day stock price information (open, high, low, and closing price) for 5,000 companies, how would you do it? You are responsible for the development, rollout and ongoing monitoring and maintenance of the feed. Describe the different methods you considered and why you would recommend your approach. The feed would be delivered once per trading day in a comma-separated format via an FTP site. The feed will be used by 1000 daily users in a web application.
What do you think iChat could improve
Don't remember the questions very well (it was a long time ago)... there were questions about experience
Design the classes and objects for a generic deck of cards that would be used in a poker game
If you had the entire text to 65 million books in a database, what would you do with it?
Coding: Write code to tokenize a string (had to explain code out loud and then follow-up with the actual code in an email
Coding: How would you find the nth to last element in a linked list?
Algorithm: Explain algorithm to shuffle cards
Imagine that there are 7 servers running in parallel. What happens when you need to expand to 20 live? What are issues? What could you do to fix this issue in the future?
Describe the classes and data structures you would use for a file system
What sort of commenting standards do you use
Coding: Jig saw puzzle. What are the data structures? Assume you have some method which can tell you if two pieces fit together. How would you solve the puzzle, minimizing the number of times you have to call that function?
From 1 - 10, rate c++, c, java, unix, sql skills
Coding: You have an array of ints. How would you find the two elements that sum to a particular value?
Coding: Implement a binary search in a sorted array
Difference between class and object
What's the max look up time for a binary tree
What's the point of inheritance?
You have a basket ball hoop and someone says that you can play 1 of 2 games. You get $1000 and one shot to get the hoop. Or, you get three shots and you have to make 2 of 3 shots. Which one do you choose? If p is the probability of making a particular shot, what value of p makes you switch games?
What's the max insertion time for a hash table